Skip to content

Commit

Permalink
Avoid unnecessary selector evaluations
Browse files Browse the repository at this point in the history
  • Loading branch information
josepot committed May 2, 2019
1 parent 6304f01 commit 1de42aa
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 6 deletions.
11 changes: 5 additions & 6 deletions src/hooks/useSelector.js
Expand Up @@ -52,10 +52,12 @@ export function useSelector(selector) {
const latestSubscriptionCallbackError = useRef()
const latestSelector = useRef(selector)

let selectedState = undefined
let latestSelectedState = useRef()

try {
selectedState = selector(store.getState())
latestSelectedState.current = useMemo(() => selector(store.getState()), [
selector
])
} catch (err) {
let errorMessage = `An error occured while selecting the store state: ${
err.message
Expand All @@ -70,11 +72,8 @@ export function useSelector(selector) {
throw new Error(errorMessage)
}

const latestSelectedState = useRef(selectedState)

useIsomorphicLayoutEffect(() => {
latestSelector.current = selector
latestSelectedState.current = selectedState
latestSubscriptionCallbackError.current = undefined
})

Expand Down Expand Up @@ -107,5 +106,5 @@ export function useSelector(selector) {
return () => subscription.tryUnsubscribe()
}, [store, subscription])

return selectedState
return latestSelectedState.current
}
28 changes: 28 additions & 0 deletions test/hooks/useSelector.spec.js
Expand Up @@ -183,6 +183,34 @@ describe('React', () => {

expect(renderedItems).toEqual([0, 0])
})

it('uses the latest selector', () => {
let selectorId = 0
let forceRender

const Comp = () => {
const [, f] = useReducer(c => c + 1, 0)
forceRender = f
const renderedSelectorId = selectorId++
const value = useSelector(() => renderedSelectorId)
renderedItems.push(value)
return <div />
}

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

rtl.act(forceRender)

// this line verifies the susbcription callback uses the same memoized selector and therefore
// does not cause a re-render
store.dispatch({ type: '' })

expect(renderedItems).toEqual([0, 1])
})
})

describe('edge cases', () => {
Expand Down

0 comments on commit 1de42aa

Please sign in to comment.