Skip to content

Commit

Permalink
Reduce unnecessary calls to useSelector selector (#1803)
Browse files Browse the repository at this point in the history
  • Loading branch information
sufian-slack committed Sep 4, 2021
1 parent e7807ef commit 099e104
Show file tree
Hide file tree
Showing 2 changed files with 80 additions and 2 deletions.
5 changes: 5 additions & 0 deletions src/hooks/useSelector.js
Expand Up @@ -65,6 +65,11 @@ function useSelectorWithStoreAndSubscription(
function checkForUpdates() {
try {
const newStoreState = store.getState()
// Avoid calling selector multiple times if the store's state has not changed
if (newStoreState === latestStoreState.current) {
return
}

const newSelectedState = latestSelector.current(newStoreState)

if (equalityFn(newSelectedState, latestSelectedState.current)) {
Expand Down
77 changes: 75 additions & 2 deletions test/hooks/useSelector.spec.js
Expand Up @@ -45,14 +45,14 @@ describe('React', () => {
})

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

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

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

Expand Down Expand Up @@ -246,6 +246,79 @@ describe('React', () => {

expect(renderedItems.length).toBe(1)
})

it('calls selector exactly once on mount and on update', () => {
store = createStore(({ count } = { count: 0 }) => ({
count: count + 1,
}))

let numCalls = 0
const selector = (s) => {
numCalls += 1
return s.count
}
const renderedItems = []

const Comp = () => {
const value = useSelector(selector)
renderedItems.push(value)
return <div />
}

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

expect(numCalls).toBe(1)
expect(renderedItems.length).toEqual(1)

store.dispatch({ type: '' })

expect(numCalls).toBe(2)
expect(renderedItems.length).toEqual(2)
})

it('calls selector twice once on mount when state changes during render', () => {
store = createStore(({ count } = { count: 0 }) => ({
count: count + 1,
}))

let numCalls = 0
const selector = (s) => {
numCalls += 1
return s.count
}
const renderedItems = []

const Child = () => {
useLayoutEffect(() => {
store.dispatch({ type: '', count: 1 })
}, [])
return <div />
}

const Comp = () => {
const value = useSelector(selector)
renderedItems.push(value)
return (
<div>
<Child />
</div>
)
}

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

// Selector first called on Comp mount, and then re-invoked after mount due to useLayoutEffect dispatching event
expect(numCalls).toBe(2)
expect(renderedItems.length).toEqual(2)
})
})

it('uses the latest selector', () => {
Expand Down

0 comments on commit 099e104

Please sign in to comment.