Skip to content

Commit 65b4a16

Browse files
otakustaynightpooltimdorr
authoredMar 22, 2021
Reuse latest selected state on selector re-run (#1654) (#1660)
Co-authored-by: nightpool <nightpool@users.noreply.github.com> Co-authored-by: Tim Dorr <timdorr@users.noreply.github.com>
1 parent 3aa8993 commit 65b4a16

File tree

2 files changed

+39
-1
lines changed

2 files changed

+39
-1
lines changed
 

‎src/hooks/useSelector.js

+10-1
Original file line numberDiff line numberDiff line change
@@ -33,7 +33,16 @@ function useSelectorWithStoreAndSubscription(
3333
storeState !== latestStoreState.current ||
3434
latestSubscriptionCallbackError.current
3535
) {
36-
selectedState = selector(storeState)
36+
const newSelectedState = selector(storeState)
37+
// ensure latest selected state is reused so that a custom equality function can result in identical references
38+
if (
39+
latestSelectedState.current === undefined ||
40+
!equalityFn(newSelectedState, latestSelectedState.current)
41+
) {
42+
selectedState = newSelectedState
43+
} else {
44+
selectedState = latestSelectedState.current
45+
}
3746
} else {
3847
selectedState = latestSelectedState.current
3948
}

‎test/hooks/useSelector.spec.js

+29
Original file line numberDiff line numberDiff line change
@@ -412,6 +412,35 @@ describe('React', () => {
412412

413413
spy.mockRestore()
414414
})
415+
416+
it('reuse latest selected state on selector re-run', () => {
417+
store = createStore(({ count } = { count: -1 }) => ({
418+
count: count + 1,
419+
}))
420+
421+
const alwaysEqual = () => true
422+
423+
const Comp = () => {
424+
// triggers render on store change
425+
useSelector((s) => s.count)
426+
const array = useSelector(() => [1, 2, 3], alwaysEqual)
427+
renderedItems.push(array)
428+
return <div />
429+
}
430+
431+
rtl.render(
432+
<ProviderMock store={store}>
433+
<Comp />
434+
</ProviderMock>
435+
)
436+
437+
expect(renderedItems.length).toBe(1)
438+
439+
store.dispatch({ type: '' })
440+
441+
expect(renderedItems.length).toBe(2)
442+
expect(renderedItems[0]).toBe(renderedItems[1])
443+
})
415444
})
416445

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

0 commit comments

Comments
 (0)
Please sign in to comment.