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

Reuse latest selected state on selector re-run (#1654) #1660

Merged
merged 2 commits into from Mar 22, 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
11 changes: 10 additions & 1 deletion src/hooks/useSelector.js
Expand Up @@ -33,7 +33,16 @@ function useSelectorWithStoreAndSubscription(
storeState !== latestStoreState.current ||
latestSubscriptionCallbackError.current
) {
selectedState = selector(storeState)
const newSelectedState = selector(storeState)
// ensure latest selected state is reused so that a custom equality function can result in identical references
if (
latestSelectedState.current === undefined ||
!equalityFn(newSelectedState, latestSelectedState.current)
) {
selectedState = newSelectedState
} else {
selectedState = latestSelectedState.current
}
} else {
selectedState = latestSelectedState.current
}
Expand Down
29 changes: 29 additions & 0 deletions test/hooks/useSelector.spec.js
Expand Up @@ -412,6 +412,35 @@ describe('React', () => {

spy.mockRestore()
})

it('reuse latest selected state on selector re-run', () => {
store = createStore(({ count } = { count: -1 }) => ({
count: count + 1,
}))

const alwaysEqual = () => true

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Does this also maintain the latest state if the equalityFn is defined within the component or inline?

Copy link
Contributor

@nightpool nightpool Dec 3, 2020

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes—it only cares what the equalityFn returns, not what its identity is. However, having a non-pure equalityFn (i.e., one that closes over variables from its surrounding components) could have very surprising results.


const Comp = () => {
// triggers render on store change
useSelector((s) => s.count)
const array = useSelector(() => [1, 2, 3], alwaysEqual)
renderedItems.push(array)
return <div />
}

rtl.render(
<ProviderMock store={store}>
<Comp />
</ProviderMock>
)

expect(renderedItems.length).toBe(1)

store.dispatch({ type: '' })

expect(renderedItems.length).toBe(2)
expect(renderedItems[0]).toBe(renderedItems[1])
})
})

describe('error handling for invalid arguments', () => {
Expand Down