MCPcopy Create free account
hub / github.com/TanStack/query / useSyncExternalStore

Function useSyncExternalStore

packages/preact-query/src/utils.ts:22–56  ·  view source on GitHub ↗
(
  subscribe: (onStoreChange: () => void) => () => void,
  getSnapshot: () => any,
)

Source from the content-addressed store, hash-verified

20 * @returns The current snapshot.
21 */
22export function useSyncExternalStore(
23 subscribe: (onStoreChange: () => void) => () => void,
24 getSnapshot: () => any,
25) {
26 const value = getSnapshot()
27
28 const [{ _instance }, forceUpdate] = useState<StoreRef>({
29 _instance: { _value: value, _getSnapshot: getSnapshot },
30 })
31
32 useLayoutEffect(() => {
33 _instance._value = value
34 _instance._getSnapshot = getSnapshot
35
36 if (didSnapshotChange(_instance)) {
37 forceUpdate({ _instance })
38 }
39 // oxlint-disable-next-line react/exhaustive-deps -- '_instance' never changes, matching the upstream implementation
40 }, [subscribe, value, getSnapshot])
41
42 useEffect(() => {
43 if (didSnapshotChange(_instance)) {
44 forceUpdate({ _instance })
45 }
46
47 return subscribe(() => {
48 if (didSnapshotChange(_instance)) {
49 forceUpdate({ _instance })
50 }
51 })
52 // oxlint-disable-next-line react/exhaustive-deps -- '_instance' never changes, matching the upstream implementation
53 }, [subscribe])
54
55 return value
56}
57
58/**
59 * Checks whether the store's snapshot changed since it was last read.

Callers 6

useBaseQueryFunction · 0.90
useMutationFunction · 0.90
useMutationStateFunction · 0.90
useQueriesFunction · 0.90
useIsFetchingFunction · 0.90

Calls 3

didSnapshotChangeFunction · 0.85
forceUpdateFunction · 0.85
subscribeFunction · 0.85

Tested by

no test coverage detected