Skip to content

Commit 719d97e

Browse files
committed
useReducer cheat mode demo to solve stale props
1 parent b68e5eb commit 719d97e

File tree

1 file changed

+14
-23
lines changed

1 file changed

+14
-23
lines changed

src/hooks/useSelector.js

Lines changed: 14 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import { useReducer, useEffect, useMemo, useContext } from 'react'
1+
import { useReducer, useEffect, useMemo, useContext, useRef } from 'react'
22
import { useReduxContext as useDefaultReduxContext } from './useReduxContext'
33
import Subscription from '../utils/Subscription'
44
import { ReactReduxContext } from '../components/Context'
@@ -11,44 +11,35 @@ function useSelectorWithStoreAndSubscription(
1111
store,
1212
contextSub
1313
) {
14+
const dispatching = useRef(false)
1415
const [state, dispatch] = useReducer(
1516
(prevState, storeState) => {
17+
if (dispatching.current) {
18+
// schedule update
19+
return { ...prevState }
20+
}
1621
const nextSelectedState = selector(storeState)
1722
if (equalityFn(nextSelectedState, prevState.selectedState)) {
1823
// bail out
1924
return prevState
2025
}
21-
return {
22-
selector,
23-
storeState,
24-
selectedState: nextSelectedState
25-
}
26+
return { selectedState: nextSelectedState }
2627
},
2728
store.getState(),
28-
storeState => ({
29-
selector,
30-
storeState,
31-
selectedState: selector(storeState)
32-
})
29+
storeState => ({ selectedState: selector(storeState) })
3330
)
3431

35-
let selectedState = state.selectedState
36-
if (state.selector !== selector) {
37-
const nextSelectedState = selector(state.storeState)
38-
if (!equalityFn(nextSelectedState, state.selectedState)) {
39-
selectedState = nextSelectedState
40-
// schedule another update
41-
dispatch(state.storeState)
42-
}
43-
}
44-
4532
const subscription = useMemo(() => new Subscription(store, contextSub), [
4633
store,
4734
contextSub
4835
])
4936

5037
useEffect(() => {
51-
const checkForUpdates = () => dispatch(store.getState())
38+
const checkForUpdates = () => {
39+
dispatching.current = true
40+
dispatch(store.getState())
41+
dispatching.current = false
42+
}
5243
subscription.onStateChange = checkForUpdates
5344
subscription.trySubscribe()
5445

@@ -57,7 +48,7 @@ function useSelectorWithStoreAndSubscription(
5748
return () => subscription.tryUnsubscribe()
5849
}, [store, subscription])
5950

60-
return selectedState
51+
return state.selectedState
6152
}
6253

6354
/**

0 commit comments

Comments
 (0)