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