白筱汐

想都是问题,做都是答案

0%

react 状态管理库 Jotai

react 状态管理库 Jotai

Jotai 是一个轻量级、原子化的状态管理库,专为 React 应用设计。与其他状态管理库(如 Redux、MobX 或 Recoil)相比,Jotai 提供了一种更简洁的方式来管理和共享状态,同时保持良好的性能和灵活性。

安装 Jotai

1
pnpm add jotai

基本用法

定义原子状态

1
2
// 定义一个原子
const counterAtom = atom(0)

使用原子状态

1
2
3
4
5
6
7
8
9
10
11
12
13
export default function Counter() {
// 使用原子
const [count, setCount] = useAtom(counterAtom)

return (
<div>
<h1>
{count}
<button onClick={() => setCount((c) => c + 1)}>add</button>
</h1>
</div>
)
}

派生原子

1
const doubleCounterAtom = atom((get) => get(counterAtom) * 2)

异步行为

1
2
3
4
5
6
7
8
9
10
const numAtom = atom(1)
const asyncReadCountAtom = atom(
// 异步读取 返回 promise
async (get) => {
await new Promise((reslove) => {
setTimeout(reslove, 1000)
});
return get(numAtom)
},
)
1
2
3
4
// 异步写
const asyncWriteCountAtom = atom(null, async (get, set) => {
set(numAtom, get(numAtom) + 1);
})

持久化存储

1
2
3
4
5
6
7
8
9
const theme = atomWithStorage('dark', false)

function ComponentUsingAsyncAtoms() {
const [asyncCount] = useAtom(asyncReadCountAtom)

return (
<p>async num: {asyncCount}</p>
)
}