跳转到内容

Zustand

Jotai 的状态存储在 React 中,但有时我们需要与 React 之外的世界进行交互。

Zustand 提供了一个 Store 接口,可用于存储一些值并与 Jotai 中的原子同步。

此扩展仅使用 Zustand 的 vanilla API。

你需要安装 zustandjotai-zustand 来使用此功能。

npm install zustand jotai-zustand

atomWithStore 使用 Zustand Store 创建一个新的原子。它是双向绑定的,你可以从两端修改值。

import { useAtom } from 'jotai'
import { atomWithStore } from 'jotai-zustand'
import create from 'zustand/vanilla'
const store = create(() => ({ count: 0 }))
const stateAtom = atomWithStore(store)
const Counter = () => {
const [state, setState] = useAtom(stateAtom)
return (
<>
count: {state.count}
<button
onClick={() => setState((prev) => ({ ...prev, count: prev.count + 1 }))}
>
button
</button>
</>
)
}

在 StackBlitz 中打开