Skip to content

Commit a208a7b

Browse files
committed
Avoid unnecessary selector evaluations
1 parent d849ede commit a208a7b

File tree

2 files changed

+94
-30
lines changed

2 files changed

+94
-30
lines changed

src/hooks/useSelector.js

Lines changed: 35 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import { useReducer, useRef, useEffect, useMemo, useLayoutEffect } from 'react'
1+
import { useState, useRef, useEffect, useMemo, useLayoutEffect } from 'react'
22
import invariant from 'invariant'
33
import { useReduxContext } from './useReduxContext'
44
import shallowEqual from '../utils/shallowEqual'
@@ -42,52 +42,36 @@ export function useSelector(selector) {
4242
invariant(selector, `You must pass a selector to useSelectors`)
4343

4444
const { store, subscription: contextSub } = useReduxContext()
45-
const [, forceRender] = useReducer(s => s + 1, 0)
45+
const [subscriptionResult, setSubscriptionResult] = useState([null])
4646

4747
const subscription = useMemo(() => new Subscription(store, contextSub), [
4848
store,
4949
contextSub
5050
])
5151

52+
const latestSelector = useRef()
53+
const latestResult = useRef()
5254
const latestSubscriptionCallbackError = useRef()
53-
const latestSelector = useRef(selector)
55+
const latestSubscriptionResult = useRef(subscriptionResult)
5456

55-
let selectedState = undefined
56-
57-
try {
58-
selectedState = selector(store.getState())
59-
} catch (err) {
60-
let errorMessage = `An error occured while selecting the store state: ${
61-
err.message
62-
}.`
63-
64-
if (latestSubscriptionCallbackError.current) {
65-
errorMessage += `\nThe error may be correlated with this previous error:\n${
66-
latestSubscriptionCallbackError.current.stack
67-
}\n\nOriginal stack trace:`
68-
}
69-
70-
throw new Error(errorMessage)
71-
}
72-
73-
const latestSelectedState = useRef(selectedState)
57+
let result = latestResult.current
7458

7559
useIsomorphicLayoutEffect(() => {
60+
latestResult.current = result
7661
latestSelector.current = selector
77-
latestSelectedState.current = selectedState
7862
latestSubscriptionCallbackError.current = undefined
63+
latestSubscriptionResult.current = subscriptionResult
7964
})
8065

8166
useIsomorphicLayoutEffect(() => {
8267
function checkForUpdates() {
68+
let newSelectedState
8369
try {
84-
const newSelectedState = latestSelector.current(store.getState())
70+
newSelectedState = latestSelector.current(store.getState())
8571

86-
if (shallowEqual(newSelectedState, latestSelectedState.current)) {
72+
if (shallowEqual(newSelectedState, latestResult.current)) {
8773
return
8874
}
89-
90-
latestSelectedState.current = newSelectedState
9175
} catch (err) {
9276
// we ignore all errors here, since when the component
9377
// is re-rendered, the selectors are called again, and
@@ -96,7 +80,9 @@ export function useSelector(selector) {
9680
latestSubscriptionCallbackError.current = err
9781
}
9882

99-
forceRender({})
83+
const newSubscriptionResult = new Array(1)
84+
newSubscriptionResult[0] = newSelectedState
85+
setSubscriptionResult(newSubscriptionResult)
10086
}
10187

10288
subscription.onStateChange = checkForUpdates
@@ -107,5 +93,25 @@ export function useSelector(selector) {
10793
return () => subscription.tryUnsubscribe()
10894
}, [store, subscription])
10995

110-
return selectedState
96+
try {
97+
return (result =
98+
selector !== latestSelector.current ||
99+
latestSubscriptionCallbackError.current
100+
? selector(store.getState())
101+
: subscriptionResult !== latestSubscriptionResult.current
102+
? subscriptionResult[0]
103+
: result)
104+
} catch (err) {
105+
let errorMessage = `An error occured while selecting the store state: ${
106+
err.message
107+
}.`
108+
109+
if (latestSubscriptionCallbackError.current) {
110+
errorMessage += `\nThe error may be correlated with this previous error:\n${
111+
latestSubscriptionCallbackError.current.stack
112+
}\n\nOriginal stack trace:`
113+
}
114+
115+
throw new Error(errorMessage)
116+
}
111117
}

test/hooks/useSelector.spec.js

Lines changed: 59 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
/*eslint-disable react/prop-types*/
22

3-
import React from 'react'
3+
import React, { useCallback, useReducer } from 'react'
44
import { createStore } from 'redux'
55
import { renderHook, act } from 'react-hooks-testing-library'
66
import * as rtl from 'react-testing-library'
@@ -31,6 +31,31 @@ describe('React', () => {
3131
expect(result.current).toEqual(0)
3232
})
3333

34+
it('always uses the latest state', () => {
35+
store = createStore(c => c + 1, -1)
36+
37+
const Comp = () => {
38+
const selector = useCallback(c => c + 1, [])
39+
const value = useSelector(selector)
40+
renderedItems.push(value)
41+
return <div />
42+
}
43+
44+
rtl.render(
45+
<ProviderMock store={store}>
46+
<Comp />
47+
</ProviderMock>
48+
)
49+
50+
expect(renderedItems).toEqual([1])
51+
52+
act(() => {
53+
store.dispatch({ type: '' })
54+
})
55+
56+
expect(renderedItems).toEqual([1, 2])
57+
})
58+
3459
it('selects the state and renders the component when the store updates', () => {
3560
const { result } = renderHook(() => useSelector(s => s.count), {
3661
wrapper: props => <ProviderMock {...props} store={store} />
@@ -156,6 +181,39 @@ describe('React', () => {
156181
})
157182
})
158183

184+
it('uses the latest selector', () => {
185+
let selectorId = 0
186+
let forceRender
187+
188+
const Comp = () => {
189+
const [, f] = useReducer(c => c + 1, 0)
190+
forceRender = f
191+
const renderedSelectorId = selectorId++
192+
const value = useSelector(() => renderedSelectorId)
193+
renderedItems.push(value)
194+
return <div />
195+
}
196+
197+
rtl.render(
198+
<ProviderMock store={store}>
199+
<Comp />
200+
</ProviderMock>
201+
)
202+
203+
expect(renderedItems).toEqual([0])
204+
205+
rtl.act(forceRender)
206+
expect(renderedItems).toEqual([0, 1])
207+
208+
rtl.act(() => {
209+
store.dispatch({ type: '' })
210+
})
211+
expect(renderedItems).toEqual([0, 1])
212+
213+
rtl.act(forceRender)
214+
expect(renderedItems).toEqual([0, 1, 2])
215+
})
216+
159217
describe('edge cases', () => {
160218
it('ignores transient errors in selector (e.g. due to stale props)', () => {
161219
const spy = jest.spyOn(console, 'error').mockImplementation(() => {})

0 commit comments

Comments
 (0)