1
- import { useReducer , useMemo , useContext } from 'react'
1
+ import { useReducer , useEffect , useMemo , useContext } from 'react'
2
2
import { useReduxContext as useDefaultReduxContext } from './useReduxContext'
3
3
import Subscription from '../utils/Subscription'
4
- import { useIsomorphicLayoutEffect } from '../utils/useIsomorphicLayoutEffect'
5
4
import { ReactReduxContext } from '../components/Context'
6
5
7
6
const refEquality = ( a , b ) => a === b
@@ -12,32 +11,51 @@ function useSelectorWithStoreAndSubscription(
12
11
store ,
13
12
contextSub
14
13
) {
15
- const [ selectedState , checkForUpdates ] = useReducer (
16
- prevSelectedState => {
17
- const nextState = store . getState ( )
18
- const nextSelectedState = selector ( nextState )
19
- if ( equalityFn ( prevSelectedState , nextSelectedState ) ) {
20
- return prevSelectedState
14
+ const [ state , dispatch ] = useReducer (
15
+ ( prevState , storeState ) => {
16
+ const nextSelectedState = selector ( storeState )
17
+ if ( equalityFn ( nextSelectedState , prevState . selectedState ) ) {
18
+ // bail out
19
+ return prevState
20
+ }
21
+ return {
22
+ selector,
23
+ storeState,
24
+ selectedState : nextSelectedState
21
25
}
22
- return nextSelectedState
23
26
} ,
24
27
store . getState ( ) ,
25
- selector
28
+ storeState => ( {
29
+ selector,
30
+ storeState,
31
+ selectedState : selector ( storeState )
32
+ } )
26
33
)
27
34
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
+
28
45
const subscription = useMemo ( ( ) => new Subscription ( store , contextSub ) , [
29
46
store ,
30
47
contextSub
31
48
] )
32
49
33
- useIsomorphicLayoutEffect ( ( ) => {
50
+ useEffect ( ( ) => {
51
+ const checkForUpdates = ( ) => dispatch ( store . getState ( ) )
34
52
subscription . onStateChange = checkForUpdates
35
53
subscription . trySubscribe ( )
36
54
37
55
checkForUpdates ( )
38
56
39
57
return ( ) => subscription . tryUnsubscribe ( )
40
- } , [ subscription ] )
58
+ } , [ store , subscription ] )
41
59
42
60
return selectedState
43
61
}
0 commit comments