@@ -4,17 +4,16 @@ import identity from 'lodash/identity'
4
4
import { shallowEqual } from './shallow-equal'
5
5
import { Ayanami } from '../core'
6
6
7
- export function useSubscribeAyanamiState < M extends Ayanami < S > , S , U > (
7
+ export function useSubscribeAyanamiState < M extends Ayanami < S > , S , U = S > (
8
8
ayanami : M ,
9
9
selector : ( state : S ) => U = identity ,
10
10
) : unknown {
11
- const state = ayanami . getState ( )
11
+ const [ state , setState ] = React . useState < U > ( ( ) => selector ( ayanami . getState ( ) ) )
12
12
13
13
const ayanamiRef = React . useRef < Ayanami < S > | null > ( null )
14
14
const subscriptionRef = React . useRef < Subscription | null > ( null )
15
- const stateRef = React . useRef < S > ( state )
16
-
17
- const [ , forceUpdate ] = React . useState ( { } )
15
+ const stateRef = React . useRef < U > ( state )
16
+ const isFirstRenderRef = React . useRef ( true )
18
17
19
18
if ( ayanamiRef . current !== ayanami ) {
20
19
ayanamiRef . current = ayanami
@@ -25,11 +24,17 @@ export function useSubscribeAyanamiState<M extends Ayanami<S>, S, U>(
25
24
}
26
25
27
26
if ( ayanami ) {
28
- subscriptionRef . current = ayanami . getState$ ( ) . subscribe ( ( state ) => {
29
- const before = selector ( stateRef . current )
30
- const after = selector ( state )
31
- if ( ! shallowEqual ( before , after ) ) forceUpdate ( { } )
32
- stateRef . current = state
27
+ subscriptionRef . current = ayanami . getState$ ( ) . subscribe ( ( moduleState ) => {
28
+ if ( isFirstRenderRef . current ) return
29
+ if ( selector === identity ) {
30
+ setState ( selector ( moduleState ) )
31
+ stateRef . current = selector ( moduleState )
32
+ } else {
33
+ const before = stateRef . current
34
+ const after = selector ( moduleState )
35
+ if ( ! shallowEqual ( before , after ) ) setState ( after )
36
+ stateRef . current = after
37
+ }
33
38
} )
34
39
}
35
40
}
@@ -43,5 +48,6 @@ export function useSubscribeAyanamiState<M extends Ayanami<S>, S, U>(
43
48
[ subscriptionRef ] ,
44
49
)
45
50
46
- return selector ( state )
51
+ isFirstRenderRef . current = false
52
+ return state
47
53
}
0 commit comments