Skip to content

Don't re-run the selector after update #1701

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Mar 25, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion src/hooks/useSelector.js
Original file line number Diff line number Diff line change
Expand Up @@ -64,13 +64,15 @@ function useSelectorWithStoreAndSubscription(
useIsomorphicLayoutEffect(() => {
function checkForUpdates() {
try {
const newSelectedState = latestSelector.current(store.getState())
const newStoreState = store.getState()
const newSelectedState = latestSelector.current(newStoreState)

if (equalityFn(newSelectedState, latestSelectedState.current)) {
return
}

latestSelectedState.current = newSelectedState
latestStoreState.current = newStoreState
} catch (err) {
// we ignore all errors here, since when the component
// is re-rendered, the selectors are called again, and
Expand Down
6 changes: 5 additions & 1 deletion test/hooks/useSelector.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -38,17 +38,21 @@ describe('React', () => {
})

it('selects the state and renders the component when the store updates', () => {
const { result } = renderHook(() => useSelector((s) => s.count), {
const selector = jest.fn((s) => s.count)

const { result } = renderHook(() => useSelector(selector), {
wrapper: (props) => <ProviderMock {...props} store={store} />,
})

expect(result.current).toEqual(0)
expect(selector).toHaveBeenCalledTimes(2)

act(() => {
store.dispatch({ type: '' })
})

expect(result.current).toEqual(1)
expect(selector).toHaveBeenCalledTimes(3)
})
})

Expand Down