forked from nanostores/react
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
24 lines (19 loc) · 715 Bytes
/
index.js
File metadata and controls
24 lines (19 loc) · 715 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
import { listenKeys } from 'nanostores'
import { useCallback, useRef, useSyncExternalStore } from 'react'
let emit = (snapshotRef, onChange) => value => {
if (snapshotRef.current === value) return
snapshotRef.current = value
onChange()
}
export function useStore(store, { keys, deps = [store, keys] } = {}) {
let snapshotRef = useRef()
snapshotRef.current = store.get()
let subscribe = useCallback(onChange => {
emit(snapshotRef, onChange)(store.value)
return keys?.length > 0
? listenKeys(store, keys, emit(snapshotRef, onChange))
: store.listen(emit(snapshotRef, onChange))
}, deps)
let get = () => snapshotRef.current
return useSyncExternalStore(subscribe, get, get)
}