( subscribe: (onStoreChange: () => void) => () => void, getSnapshot: () => any, )
| 20 | * @returns The current snapshot. |
| 21 | */ |
| 22 | export 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. |
no test coverage detected