pocket-state 0.0.2 → 0.0.3

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.0.2",
3
+ "version": "0.0.3",
4
4
  "description": "tiny global store",
5
5
  "main": "src/index",
6
6
  "codegenConfig": {
@@ -1,7 +1,8 @@
1
1
  // useStore.ts
2
- import {useCallback} from 'react';
2
+ import {useCallback, useRef} from 'react';
3
3
  import {useSyncExternalStore} from 'react';
4
4
  import type {Store} from './type';
5
+ import {shallow} from './shallowEqual';
5
6
 
6
7
  export function useStore<T>(store: Store<T>): T;
7
8
  export function useStore<T, S>(store: Store<T>, selector: (state: T) => S): S;
@@ -24,3 +25,34 @@ export function useStore<T, S = T>(
24
25
 
25
26
  return useSyncExternalStore(subscribe, getSnapshot, getSnapshot) as T | S;
26
27
  }
28
+
29
+ //shallow
30
+ export function useShallowStore<T, S>(
31
+ store: Store<T>,
32
+ selector: (state: T) => S,
33
+ ): S {
34
+ const selectorRef = useRef(selector);
35
+ selectorRef.current = selector;
36
+
37
+ const lastSliceRef = useRef<S>(selector(store.getValue()));
38
+
39
+ const subscribe = (onChange: () => void) => {
40
+ return store.subscribe((nextState: T) => {
41
+ const nextSlice = selectorRef.current(nextState);
42
+ if (!shallow(lastSliceRef.current as any, nextSlice as any)) {
43
+ lastSliceRef.current = nextSlice;
44
+ onChange();
45
+ }
46
+ });
47
+ };
48
+
49
+ const getSnapshot = () => {
50
+ const current = selectorRef.current(store.getValue());
51
+ if (!shallow(lastSliceRef.current as any, current as any)) {
52
+ lastSliceRef.current = current;
53
+ }
54
+ return lastSliceRef.current;
55
+ };
56
+
57
+ return useSyncExternalStore(subscribe, getSnapshot, getSnapshot);
58
+ }