Skip to content

Commit 10cf5f4

Browse files
committed
Avoid unnecessary selector evaluations
1 parent d849ede commit 10cf5f4

File tree

2 files changed

+109
-28
lines changed

2 files changed

+109
-28
lines changed

src/hooks/useSelector.js

Lines changed: 50 additions & 27 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,37 @@ 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() {
8368
try {
8469
const newSelectedState = latestSelector.current(store.getState())
8570

86-
if (shallowEqual(newSelectedState, latestSelectedState.current)) {
71+
if (shallowEqual(newSelectedState, latestResult.current)) {
8772
return
8873
}
8974

90-
latestSelectedState.current = newSelectedState
75+
latestResult.current = newSelectedState
9176
} catch (err) {
9277
// we ignore all errors here, since when the component
9378
// is re-rendered, the selectors are called again, and
@@ -96,7 +81,9 @@ export function useSelector(selector) {
9681
latestSubscriptionCallbackError.current = err
9782
}
9883

99-
forceRender({})
84+
const newSubscriptionResult = new Array(1)
85+
newSubscriptionResult[0] = latestResult.current
86+
setSubscriptionResult(newSubscriptionResult)
10087
}
10188

10289
subscription.onStateChange = checkForUpdates
@@ -107,5 +94,41 @@ export function useSelector(selector) {
10794
return () => subscription.tryUnsubscribe()
10895
}, [store, subscription])
10996

110-
return selectedState
97+
try {
98+
// If the selector has changed, then it has to be re-evaluated
99+
if (selector !== latestSelector.current) {
100+
return (result = selector(store.getState()))
101+
}
102+
103+
// If the subscriptionResult is different, that means that this
104+
// update has been triggered from the subscription
105+
if (subscriptionResult != latestSubscriptionResult.current) {
106+
// Before we return the result that was calculated during
107+
// the subscription we need to check whether an error
108+
// ocurred during the computation. If that is the case,
109+
// then we re-evaluate the selector with the latest state
110+
if (latestSubscriptionCallbackError.current) {
111+
return (result = selector(store.getState()))
112+
}
113+
114+
// At this point we know for sure that it is safe to return
115+
// the result that was computed inside the subscription
116+
return (result = subscriptionResult[0])
117+
}
118+
119+
// We just prevented an unnecessary re-evaluation of the selector!
120+
return result
121+
} catch (err) {
122+
let errorMessage = `An error occured while selecting the store state: ${
123+
err.message
124+
}.`
125+
126+
if (latestSubscriptionCallbackError.current) {
127+
errorMessage += `\nThe error may be correlated with this previous error:\n${
128+
latestSubscriptionCallbackError.current.stack
129+
}\n\nOriginal stack trace:`
130+
}
131+
132+
throw new Error(errorMessage)
133+
}
111134
}

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)