UNPKG

shelving

Version:

Toolkit for using data in JavaScript.

18 lines (17 loc) 913 B
import { useSyncExternalStore } from "react"; import { NONE } from "../util/constants.js"; import { BLACKHOLE } from "../util/function.js"; import { runSequence } from "../util/sequence.js"; import { useProps } from "./useProps.js"; export function useStore(store) { // Store memoized versions of `subscribe()` and `getSnapshot()` so `useSyncExternalStore()` doesn't re-subscribe on every render. const internals = useProps(); // Update `internals` if `store` changes. if (store !== internals.store || !internals.subscribe || !internals.getSnapshot) { internals.subscribe = onStoreChange => (store ? runSequence(store, onStoreChange, onStoreChange) : BLACKHOLE); internals.getSnapshot = () => (!store ? undefined : store.loading ? NONE : store.value); internals.store = store; } useSyncExternalStore(internals.subscribe, internals.getSnapshot); return store; }