MCPcopy
hub / github.com/preactjs/preact / useSyncExternalStore

Function useSyncExternalStore

compat/src/hooks.js:9–42  ·  view source on GitHub ↗
(subscribe, getSnapshot)

Source from the content-addressed store, hash-verified

7 * @typedef {{ _value: any; _getSnapshot: () => any }} Store
8 */
9export function useSyncExternalStore(subscribe, getSnapshot) {
10 const value = getSnapshot();
11
12 /**
13 * @typedef {{ _instance: Store }} StoreRef
14 * @type {[StoreRef, (store: StoreRef) => void]}
15 */
16 const [{ _instance }, forceUpdate] = useState({
17 _instance: { _value: value, _getSnapshot: getSnapshot }
18 });
19
20 useLayoutEffect(() => {
21 _instance._value = value;
22 _instance._getSnapshot = getSnapshot;
23
24 if (didSnapshotChange(_instance)) {
25 forceUpdate({ _instance });
26 }
27 }, [subscribe, value, getSnapshot]);
28
29 useEffect(() => {
30 if (didSnapshotChange(_instance)) {
31 forceUpdate({ _instance });
32 }
33
34 return subscribe(() => {
35 if (didSnapshotChange(_instance)) {
36 forceUpdate({ _instance });
37 }
38 });
39 }, [subscribe]);
40
41 return value;
42}
43
44/** @type {(inst: Store) => boolean} */
45function didSnapshotChange(inst) {

Callers 5

AppFunction · 0.90
AFunction · 0.90
BFunction · 0.90
Child1Function · 0.90
Child2Function · 0.90

Calls 5

useStateFunction · 0.90
useLayoutEffectFunction · 0.90
useEffectFunction · 0.90
didSnapshotChangeFunction · 0.85
subscribeFunction · 0.50

Tested by 5

AppFunction · 0.72
AFunction · 0.72
BFunction · 0.72
Child1Function · 0.72
Child2Function · 0.72

Used in the wild real call sites across dependent graphs

searching dependent graphs…