shelving
Version:
Toolkit for using data in JavaScript.
19 lines (18 loc) • 949 B
JavaScript
import { useSyncExternalStore } from "react";
import { NONE } from "../util/constants.js";
import { BLACKHOLE } from "../util/function.js";
import { runSequence } from "../util/sequence.js";
import { useInternals } from "./useInternals.js";
export function useStore(store) {
// Store memoized versions of `subscribe()` and `getSnapshot()` so `useSyncExternalStore()` doesn't re-subscribe on every render.
const internals = useInternals();
// Update `internals` if `store` changes.
if (store !== internals.store) {
internals.subscribe = onStoreChange => (store ? runSequence(store, onStoreChange, onStoreChange) : BLACKHOLE);
internals.getSnapshot = () => (!store ? undefined : store.loading ? NONE : store.value);
internals.store = store;
}
// biome-ignore lint/style/noNonNullAssertion: We know these are set.
useSyncExternalStore(internals.subscribe, internals.getSnapshot);
return store;
}