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 CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pocket-state",
3
- "version": "0.1.13",
3
+ "version": "0.1.14",
4
4
  "description": "tiny global store",
5
5
  "main": "src/index",
6
6
  "codegenConfig": {
@@ -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 getSnapshot = useCallback(
9
- () =>
10
- selector
11
- ? selector(store.getValue())
12
- : (store.getValue() as unknown as S),
13
- [store, selector],
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, selector],
26
+ [store],
26
27
  );
27
28
 
28
29
  return useSyncExternalStore(subscribe, getSnapshot, getSnapshot);