UNPKG

shelving

Version:

Toolkit for using data in JavaScript.

20 lines (19 loc) 745 B
import { useSyncExternalStore } from "react"; import { BLACKHOLE } from "../util/function.js"; import { STOPHOLE } from "../util/index.js"; // We add an `[EXTERNAL_STORE]` symbol key to the `Store` instance to cache the subscribe and getSnapshot functions for `useSyncExternalStore()`. const EXTERNAL_STORE = Symbol(); const EXTERNAL_BLACKHOLE = { subscribe: STOPHOLE, getSnapshot: BLACKHOLE, }; export function useStore(store) { const { subscribe, getSnapshot } = !store ? EXTERNAL_BLACKHOLE : (store[EXTERNAL_STORE] ??= { subscribe: c => store.subscribe(c, c), getSnapshot: () => store.snapshot, }); useSyncExternalStore(subscribe, getSnapshot, getSnapshot); return store; }