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 CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pocket-state",
3
- "version": "0.1.16",
3
+ "version": "0.1.17",
4
4
  "description": "tiny global store",
5
5
  "main": "src/index",
6
6
  "codegenConfig": {
@@ -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 sliceRef = useRef<S>(
9
- selector ? selector(store.getValue()) : (store.getValue() as unknown as S),
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
- if (selector) {
15
- return store.subscribe(selector, (nextSlice: S) => {
16
- sliceRef.current = nextSlice;
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, selector],
21
+ [store, sel],
26
22
  );
27
- const getSnapshot = useCallback(() => sliceRef.current, []);
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
  }