pocket-state 0.1.15 → 0.1.17
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +1 -1
- package/src/globalState/hooks.ts +22 -19
package/package.json
CHANGED
package/src/globalState/hooks.ts
CHANGED
|
@@ -1,31 +1,34 @@
|
|
|
1
|
-
import {useCallback} from 'react';
|
|
1
|
+
import {useCallback, useRef, useSyncExternalStore} from 'react';
|
|
2
2
|
import type {Store} from './type';
|
|
3
|
-
import {useSyncExternalStoreWithSelector} from 'use-sync-external-store/shim/with-selector';
|
|
4
3
|
|
|
5
|
-
const identity = <T>(s: T) => s;
|
|
6
4
|
export function useStore<T, S = T>(
|
|
7
5
|
store: Store<T>,
|
|
8
6
|
selector?: (state: T) => S,
|
|
9
|
-
isEqual?: (a: S, b: S) => boolean,
|
|
10
7
|
): S {
|
|
8
|
+
const sel = selector ?? ((s: T) => s as unknown as S);
|
|
9
|
+
|
|
10
|
+
const lastStateRef = useRef<T>(store.getValue());
|
|
11
|
+
const lastSliceRef = useRef<S>(sel(lastStateRef.current));
|
|
12
|
+
|
|
11
13
|
const subscribe = useCallback(
|
|
12
|
-
(
|
|
13
|
-
return store.subscribe(() =>
|
|
14
|
+
(onChange: () => void) => {
|
|
15
|
+
return store.subscribe(sel, (nextSlice: S) => {
|
|
16
|
+
lastStateRef.current = store.getValue();
|
|
17
|
+
lastSliceRef.current = nextSlice;
|
|
18
|
+
onChange();
|
|
19
|
+
});
|
|
14
20
|
},
|
|
15
|
-
[store],
|
|
21
|
+
[store, sel],
|
|
16
22
|
);
|
|
17
23
|
|
|
18
|
-
const getSnapshot =
|
|
19
|
-
|
|
24
|
+
const getSnapshot = useCallback(() => {
|
|
25
|
+
const s = store.getValue();
|
|
26
|
+
if (s !== lastStateRef.current) {
|
|
27
|
+
lastStateRef.current = s;
|
|
28
|
+
lastSliceRef.current = sel(s);
|
|
29
|
+
}
|
|
30
|
+
return lastSliceRef.current;
|
|
31
|
+
}, [store, sel]);
|
|
20
32
|
|
|
21
|
-
|
|
22
|
-
const eq = isEqual ?? Object.is;
|
|
23
|
-
|
|
24
|
-
return useSyncExternalStoreWithSelector(
|
|
25
|
-
subscribe,
|
|
26
|
-
getSnapshot,
|
|
27
|
-
getServerSnapshot,
|
|
28
|
-
sel,
|
|
29
|
-
eq,
|
|
30
|
-
);
|
|
33
|
+
return useSyncExternalStore(subscribe, getSnapshot, getSnapshot);
|
|
31
34
|
}
|