探索现代 React 生态中最简洁的状态管理方案,体验"钩子即状态"的开发模式
{{ getZustandFileContent() }}
{{ apiResponse }}
import { atom } from 'jotai'
import { atomFamily } from 'jotai/utils'
// 基础原子
const countAtom = atom(0)
// 派生原子 - 自动追踪依赖
const doubleAtom = atom((get) => get(countAtom) * 2)
const isEvenAtom = atom((get) => get(countAtom) % 2 === 0)
// 可写派生原子
const countAndDoubleAtom = atom(
(get) => ({
count: get(countAtom),
double: get(doubleAtom)
}),
(get, set, newCount) => {
set(countAtom, newCount)
}
)
// 原子家族 - 动态创建原子
const todoAtomFamily = atomFamily((id) =>
atom({ id, text: '', completed: false })
)
// 异步原子
const userAtom = atom(null)
const fetchUserAtom = atom(
(get) => get(userAtom),
async (get, set, userId) => {
const response = await fetch(\`/api/users/\${userId}\`)
const user = await response.json()
set(userAtom, user)
}
)
export {
countAtom,
doubleAtom,
isEvenAtom,
countAndDoubleAtom,
todoAtomFamily,
fetchUserAtom
}