3
3
// https://github.com/facebook/react/blob/8d74e8c73a5cc5e461bb1413a74c6b058c6be134/packages/use-sync-external-store/src/useSyncExternalStoreWithSelector.js
4
4
// MIT Licensed https://github.com/facebook/react/blob/be8aa76873e231555676483a36534bb48ad1b1a3/LICENSE
5
5
6
- import { useDebugValue , useEffect , useMemo , useRef , useSyncExternalStore } from 'react'
6
+ import { useEffect , useMemo , useRef , useSyncExternalStore } from 'react'
7
7
8
8
const NIL = Symbol ( 'NIL' )
9
9
10
10
export function useSyncExternalStoreWithSelector < Snapshot , Selection > (
11
11
subscribe : ( onStoreChange : ( ) => void ) => ( ) => void ,
12
12
getSnapshot : ( ) => Snapshot ,
13
13
selector : ( snapshot : Snapshot ) => Selection ,
14
- isEqual : ( a : Selection , b : Selection ) => boolean ,
14
+ isEqual : ( a : Selection , b : Selection ) => boolean = Object . is ,
15
15
) : Selection {
16
16
// Use this to track the rendered snapshot.
17
- const selectionRef = useRef < Selection | typeof NIL > ( NIL )
17
+ const instRef = useRef < Selection | typeof NIL > ( NIL )
18
18
19
19
const getSelection = useMemo ( ( ) => {
20
20
// Track the memoized state using closure variables that are local to this
@@ -33,10 +33,12 @@ export function useSyncExternalStoreWithSelector<Snapshot, Selection>(
33
33
// Even if the selector has changed, the currently rendered selection
34
34
// may be equal to the new selection. We should attempt to reuse the
35
35
// current value if possible, to preserve downstream memoizations.
36
- const currentSelection = selectionRef . current
37
- if ( currentSelection !== NIL && isEqual ( currentSelection , nextSelection ) ) {
38
- memoizedSelection = currentSelection
39
- return currentSelection
36
+ if ( instRef . current !== NIL ) {
37
+ const currentSelection = instRef . current
38
+ if ( isEqual ( currentSelection , nextSelection ) ) {
39
+ memoizedSelection = currentSelection
40
+ return currentSelection
41
+ }
40
42
}
41
43
memoizedSelection = nextSelection
42
44
return nextSelection
@@ -77,9 +79,8 @@ export function useSyncExternalStoreWithSelector<Snapshot, Selection>(
77
79
const selection = useSyncExternalStore ( subscribe , getSelection )
78
80
79
81
useEffect ( ( ) => {
80
- selectionRef . current = selection
82
+ instRef . current = selection
81
83
} , [ selection ] )
82
84
83
- useDebugValue ( selection )
84
85
return selection
85
86
}
0 commit comments