Skip to content
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

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

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.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
4 changes: 3 additions & 1 deletion src/hooks/useSelector.js
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
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