pocket-state 0.1.13 → 0.1.14
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 +13 -12
package/package.json
CHANGED
package/src/globalState/hooks.ts
CHANGED
|
@@ -1,28 +1,29 @@
|
|
|
1
|
-
import {useCallback, useSyncExternalStore} from 'react';
|
|
1
|
+
import {useCallback, useRef, useSyncExternalStore} from 'react';
|
|
2
2
|
import type {Store} from './type';
|
|
3
|
+
import {shallow} from './shallowEqual';
|
|
3
4
|
|
|
4
5
|
export function useStore<T, S = T>(
|
|
5
6
|
store: Store<T>,
|
|
6
7
|
selector?: (state: T) => S,
|
|
8
|
+
isEqual = shallow,
|
|
7
9
|
): S {
|
|
8
|
-
const
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
10
|
+
const select = (s: T): S => (selector ? selector(s) : (s as unknown as S));
|
|
11
|
+
const lastRef = useRef<S>(select(store.getValue()));
|
|
12
|
+
const getSnapshot = useCallback(() => {
|
|
13
|
+
const next = select(store.getValue());
|
|
14
|
+
if (!isEqual(next, lastRef.current)) {
|
|
15
|
+
lastRef.current = next;
|
|
16
|
+
}
|
|
17
|
+
return lastRef.current;
|
|
18
|
+
}, [store, selector, isEqual]);
|
|
15
19
|
|
|
16
20
|
const subscribe = useCallback(
|
|
17
21
|
(onChange: () => void) => {
|
|
18
|
-
if (selector && store.subscribe) {
|
|
19
|
-
return store.subscribe(selector, onChange);
|
|
20
|
-
}
|
|
21
22
|
return store.subscribe(() => {
|
|
22
23
|
onChange();
|
|
23
24
|
});
|
|
24
25
|
},
|
|
25
|
-
[store
|
|
26
|
+
[store],
|
|
26
27
|
);
|
|
27
28
|
|
|
28
29
|
return useSyncExternalStore(subscribe, getSnapshot, getSnapshot);
|