-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
46 lines (36 loc) · 1.06 KB
/
index.js
File metadata and controls
46 lines (36 loc) · 1.06 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
40
41
42
43
44
45
46
import { useSyncExternalStore } from "react";
const store = new Map();
const initializeStateInStore = (key, initial) => {
if (!store.has(key)) {
store.set(key, {
value: initial,
listeners: new Set(),
})
}
}
const subscribeToStore = (key, listener) => {
const entry = store.get(key);
if (!entry) return () => { };
entry.listeners.add(listener);
return () => entry.listeners.delete(listener);
}
const getSnapshotFromStore = (key) => {
const entry = store.get(key)
return entry?.value
}
const setStateInStoree = (key, newValue) => {
const entry = store.get(key)
if (entry) {
entry.value = newValue;
entry.listeners.forEach((fn) => fn());
}
}
const useGlobalState = (key, initialValue) => {
initializeStateInStore(key, initialValue);
const globalState = useSyncExternalStore(
(cb) => subscribeToStore(key, cb),
() => getSnapshotFromStore(key)
);
return [globalState, (newValue) => setStateInStoree(key, newValue)]
}
export default useGlobalState;