(subscribe, getSnapshot)
| 7 | * @typedef {{ _value: any; _getSnapshot: () => any }} Store |
| 8 | */ |
| 9 | export 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} */ |
| 45 | function didSnapshotChange(inst) { |
searching dependent graphs…