jotai-ssr
Version:
Jotai utilities for server-side rendering (SSR)
30 lines (29 loc) • 1.33 kB
JavaScript
import { atom, useStore } from 'jotai';
import { useCallback, useEffect, useRef } from 'react';
export function useHydrateAtoms(hydrateAtoms, options) {
const isHydratedRef = useRef(false);
const lastHydrateAtoms = useRef(hydrateAtoms);
const store = useStore((options === null || options === void 0 ? void 0 : options.store) != null ? { store: options === null || options === void 0 ? void 0 : options.store } : undefined);
const hydrate = useCallback(() => {
store.set(isHydratingPrimitiveAtom, true);
for (const [atom, ...args] of hydrateAtoms) {
store.set(atom, ...args);
}
store.set(isHydratingPrimitiveAtom, false);
isHydratedRef.current = true;
}, [store, hydrateAtoms]);
if (!isHydratedRef.current) {
hydrate();
}
useEffect(() => {
if (!(options === null || options === void 0 ? void 0 : options.enableReHydrate)) {
return;
}
if (hydrateAtoms !== lastHydrateAtoms.current) {
lastHydrateAtoms.current = hydrateAtoms;
hydrate();
}
}, [hydrate, options === null || options === void 0 ? void 0 : options.enableReHydrate, hydrateAtoms]);
}
const isHydratingPrimitiveAtom = atom(false);
export const isHydratingAtom = atom((get) => get(isHydratingPrimitiveAtom));