@@ -4,17 +4,16 @@ import identity from 'lodash/identity'
44import { shallowEqual } from './shallow-equal'
55import { Ayanami } from '../core'
66
7- export function useSubscribeAyanamiState < M extends Ayanami < S > , S , U > (
7+ export function useSubscribeAyanamiState < M extends Ayanami < S > , S , U = S > (
88 ayanami : M ,
99 selector : ( state : S ) => U = identity ,
1010) : unknown {
11- const state = ayanami . getState ( )
11+ const [ state , setState ] = React . useState < U > ( ( ) => selector ( ayanami . getState ( ) ) )
1212
1313 const ayanamiRef = React . useRef < Ayanami < S > | null > ( null )
1414 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 )
1817
1918 if ( ayanamiRef . current !== ayanami ) {
2019 ayanamiRef . current = ayanami
@@ -25,11 +24,17 @@ export function useSubscribeAyanamiState<M extends Ayanami<S>, S, U>(
2524 }
2625
2726 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+ }
3338 } )
3439 }
3540 }
@@ -43,5 +48,6 @@ export function useSubscribeAyanamiState<M extends Ayanami<S>, S, U>(
4348 [ subscriptionRef ] ,
4449 )
4550
46- return selector ( state )
51+ isFirstRenderRef . current = false
52+ return state
4753}
0 commit comments