UNPKG

@mongez/react-atom

Version:
60 lines (57 loc) 2.11 kB
"use client"; import React, { createContext, useContext, useEffect, useState } from "react"; import { createAtomStore } from "@mongez/atom"; import { jsx } from "react/jsx-runtime"; //#region ../@mongez/react-atom/src/store.tsx /** * React context that holds the active atom store. Components that read or * write atoms via the React hooks resolve the store-scoped clone from this * context. When the context is null (no provider mounted), hooks fall back * to the module-level singleton atom, which is the right behavior for a * client-only SPA. */ const AtomStoreContext = createContext(null); /** * Provider that scopes atom reads and writes to a request-local `AtomStore`. * * Wrap the root of your component tree (or any subtree) with this provider * to give that subtree its own isolated copy of every atom's state. This is * the supported pattern for SSR in Next.js, Remix, and TanStack Start — * each request creates its own store, so concurrent requests cannot see * each other's state. * * Without a provider, atoms fall back to the module-level singleton (the * historical client-only behavior). */ function AtomStoreProvider({ store, initialAtoms, initialValues, children }) { const [activeStore] = useState(() => { const next = store ?? createAtomStore(); if (initialAtoms) for (const atomTemplate of initialAtoms) next.use(atomTemplate); if (initialValues) next.hydrate(initialValues); return next; }); useEffect(() => { return () => { if (!store) activeStore.destroy(); }; }, [activeStore, store]); return /* @__PURE__ */ jsx(AtomStoreContext.Provider, { value: activeStore, children }); } /** * Read the active atom store. Returns null when no `<AtomStoreProvider>` is * mounted in the tree above this component. */ function useAtomStore() { return useContext(AtomStoreContext); } function useAtom(arg) { const store = useContext(AtomStoreContext); if (typeof arg === "string") return store?.get(arg); return store ? store.use(arg) : arg; } //#endregion export { AtomStoreContext, AtomStoreProvider, useAtom, useAtomStore }; //# sourceMappingURL=store.mjs.map