JotaiJotai

状態
Primitive and flexible state management for React

useHydrateAtoms

引用: https://github.com/pmndrs/jotai/issues/340

使用

import { atom, useAtom } from "jotai";
import { useHydrateAtoms } from "jotai/utils";
const countAtom = atom(0);
const CounterPage = ({ countFromServer }) => {
useHydrateAtoms([[countAtom, countFromServer]]);
const [count] = useAtom(countAtom);
// count 将是 countFromServer 的值,而不是 0。
};

useHydrateAtoms 的主要用例是像 Next.js 这样的 SSR 应用程序,其中初始值是例如 在服务器上获取,可以通过 props 传递给组件。

// 定义
function useHydrateAtoms(
values: Iterable<readonly [Atom<unknown>, unknown]>,
scope?: Scope
): void;

该 hook 采用包含 [atom, value] 的可迭代元组作为参数和可选范围。

// 与数组一起使用,指定范围
useHydrateAtoms(
[
[countAtom, 42],
[frameworkAtom, "Next.js"],
],
myScope
);
// 或者用 map
const [initialValues] = useState(() => new Map([[count, 42]]));
useHydrateAtoms(initialValues);

每个作用域中的原子只能 hydrated 一次。 因此,如果在重新渲染期间更改了使用的初始值,则不会更新原子值。

如果需要在多个范围内进行 hydrated,请使用多个 useHydrateAtoms hook 来实现。

useHydrateAtoms([
[countAtom, 42],
[frameworkAtom, "Next.js"],
]);
useHydrateAtoms(
[
[countAtom, 17],
[frameworkAtom, "Gatsby"],
],
myScope
);

Codesandbox

Next.js 部分 中有更多示例。