pocket-state 0.1.16 → 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 +17 -13
package/package.json
CHANGED
package/src/globalState/hooks.ts
CHANGED
|
@@ -5,26 +5,30 @@ export function useStore<T, S = T>(
|
|
|
5
5
|
store: Store<T>,
|
|
6
6
|
selector?: (state: T) => S,
|
|
7
7
|
): S {
|
|
8
|
-
const
|
|
9
|
-
|
|
10
|
-
);
|
|
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));
|
|
11
12
|
|
|
12
13
|
const subscribe = useCallback(
|
|
13
14
|
(onChange: () => void) => {
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
onChange();
|
|
18
|
-
});
|
|
19
|
-
}
|
|
20
|
-
return store.subscribe((next: T) => {
|
|
21
|
-
sliceRef.current = next as unknown as S;
|
|
15
|
+
return store.subscribe(sel, (nextSlice: S) => {
|
|
16
|
+
lastStateRef.current = store.getValue();
|
|
17
|
+
lastSliceRef.current = nextSlice;
|
|
22
18
|
onChange();
|
|
23
19
|
});
|
|
24
20
|
},
|
|
25
|
-
[store,
|
|
21
|
+
[store, sel],
|
|
26
22
|
);
|
|
27
|
-
|
|
23
|
+
|
|
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]);
|
|
28
32
|
|
|
29
33
|
return useSyncExternalStore(subscribe, getSnapshot, getSnapshot);
|
|
30
34
|
}
|