pocket-state 0.1.20 → 0.1.22

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.20",
3
+ "version": "0.1.22",
4
4
  "description": "tiny global store",
5
5
  "main": "src/index",
6
6
  "codegenConfig": {
@@ -1,31 +1,42 @@
1
1
  import {useCallback, useRef, useSyncExternalStore} from 'react';
2
2
  import type {Store} from './type';
3
+ import {shallow} from '../utils/shallowEqual';
4
+
5
+ type EqualityFn<S> = (a: any, b: any) => boolean;
6
+
7
+ // Overloads
8
+ export function useStore<T>(store: Store<T>): T;
9
+ export function useStore<T, S>(
10
+ store: Store<T>,
11
+ selector: (state: T) => S,
12
+ equalityFn?: EqualityFn<S>,
13
+ ): S;
3
14
 
4
15
  export function useStore<T, S = T>(
5
16
  store: Store<T>,
6
17
  selector?: (state: T) => S,
18
+ equalityFn: EqualityFn<S> = shallow,
7
19
  ): S {
8
20
  const sel = selector ?? ((s: T) => s as unknown as S);
9
21
 
10
-
11
- const lastStateRef = useRef<T>(store.getValue());
12
- const lastSliceRef = useRef<S>(sel(lastStateRef.current));
22
+ const sliceRef = useRef<S>(sel(store.getValue()));
23
+ const eqFn = selector ? equalityFn : Object.is;
13
24
 
14
25
  const subscribe = useCallback((onChange: () => void) => {
15
- return store.subscribe(sel, (nextSlice: S) => {
16
- lastStateRef.current = store.getValue();
17
- lastSliceRef.current = nextSlice;
18
- onChange();
26
+ return store.subscribe(sel, (_prev: S, next: S) => {
27
+ if (!eqFn(sliceRef.current, next)) {
28
+ sliceRef.current = next;
29
+ onChange();
30
+ }
19
31
  });
20
32
  }, []);
21
33
 
22
34
  const getSnapshot = useCallback(() => {
23
- const s = store.getValue();
24
- if (s !== lastStateRef.current) {
25
- lastStateRef.current = s;
26
- lastSliceRef.current = sel(s);
35
+ const next = sel(store.getValue());
36
+ if (!eqFn(sliceRef.current, next)) {
37
+ sliceRef.current = next;
27
38
  }
28
- return lastSliceRef.current;
39
+ return sliceRef.current;
29
40
  }, []);
30
41
 
31
42
  return useSyncExternalStore(subscribe, getSnapshot, getSnapshot);
@@ -56,8 +56,8 @@ export function createStore<T>(
56
56
  wrapped = (next: T) => {
57
57
  const slice = selector(next);
58
58
  if (!areEqual(slice, prevSlice)) {
59
- prevSlice = slice;
60
59
  maybeListener(prevSlice, slice);
60
+ prevSlice = slice;
61
61
  }
62
62
  };
63
63
  } else {
@@ -65,8 +65,8 @@ export function createStore<T>(
65
65
  let prev = state;
66
66
  wrapped = (next: T) => {
67
67
  if (!areEqual(next, prev)) {
68
- prev = next;
69
68
  listener(prev, next);
69
+ prev = next;
70
70
  }
71
71
  };
72
72
  }