@stainless-code/persist
Version:
Hydration-aware persistence middleware for reactive stores (storage × codec seams, TanStack Store adapters, React hydration hook)
30 lines (29 loc) • 1.24 kB
JavaScript
import { useSyncExternalStore } from "react";
//#region src/use-hydrated.ts
const noopSubscribe = () => () => {};
const alwaysTrue = () => true;
/**
* Mount a `HydrationSignal` into the React lifecycle via `useSyncExternalStore`.
* Returns ONLY `hydrated` — state reads go through `useSelector`. Null signal →
* `hydrated: true` (store stays the same with or without persistence). Server
* snapshot is always `true` (no storage server-side, nothing to gate) — the
* SSR policy every framework adapter must implement per the
* `HydrationSignal` adapter contract; this hook is the reference.
*
* @example
* ```ts
* // store module — hydration signal as a persist sidekick
* const persist = persistStore(store, { name: "app:prefs:v1" });
* export const prefsHydration = toHydrationSignal(persist);
*
* // component — gate the hydrate flash, read state via useSelector as usual
* const { hydrated } = useHydrated(prefsHydration);
* const prefs = useSelector(store, (s) => s.prefs);
* if (!hydrated) return <Skeleton />;
* ```
*/
function useHydrated(signal) {
return { hydrated: useSyncExternalStore(signal?.subscribeHydrated ?? noopSubscribe, signal?.isHydrated ?? alwaysTrue, alwaysTrue) };
}
//#endregion
export { useHydrated };