-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhooks.ts
More file actions
39 lines (29 loc) · 1.2 KB
/
hooks.ts
File metadata and controls
39 lines (29 loc) · 1.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
import { useCallback, useEffect, useState } from 'react';
import { Store } from './store';
import { type SetterFunc, SET_STATE } from './types';
export const useStore = <State>(store: Store<State>) => {
const [_, update] = useState<number>(0);
const reRender = useCallback(() => update((count: number) => ++count), []);
store.attachComponent(reRender);
useEffect(() => () => { store.detachComponent() }, [store]);
const get = () => store.get();
const set = (setter: SetterFunc<State>) => store.set(setter);
return { set, get, store };
}
export const useStoreSelector = <State, Selected>(
store: Store<State>,
selector: (state: State) => Selected
) => {
const [selected, setSelected] = useState(() => selector(store.get()));
useEffect(() => {
const handler = (state: State) => {
const newSelected = selector(state);
if (!Object.is(newSelected, selected)) {
setSelected(newSelected);
}
};
store.onSetState(handler);
return () => { store.unsubscribe(SET_STATE, store.getLastSubscriberId()); }
}, [store, selector, selected]);
return selected;
};