原子状态模型(Jotai、Recoil)从许多小的、独立的单元(称为atoms)自下而上地构建全局状态,而不是一个大的自上而下的存储(Redux)或单块上下文。组件订阅单个原子,仅在这些原子发生变化时才重新渲染。
Atoms — 状态的最小单位
jsx
{ atom, useAtom } ;
countAtom = ();
nameAtom = ();
每个原子都是状态的自包含片段。您可以根据需要创建尽可能多的原子,每个原子都可以单独寻址。
// a derived atom computes from other atoms; recomputes when its dependencies change
const doubleAtom = atom((get) => get(countAtom) * 2);
const greetingAtom = atom((get) => `Hello, ${get(nameAtom)}`);
// writable derived atom
const upperNameAtom = atom(
(get) => get(nameAtom).toUpperCase(),
(get, set, newVal) => set(nameAtom, newVal.toLowerCase()),
);
原子组合成一个依赖图 — 派生原子在其读取的原子发生变化时自动更新,就像电子表格一样。
function Counter() {
const [count, setCount] = useAtom(countAtom); // global, but useState-like API
return <button onClick={() => setCount(count + 1)}>{count}</button>;
}
function Display() {
const [double] = useAtom(doubleAtom); // re-renders ONLY when doubleAtom changes
}
Redux (top-down): one big state tree; you carve slices/selectors OUT of it
Atomic (bottom-up): start with tiny atoms; compose them UP into derived state
Granularity: each atom is independently subscribable → naturally fine-grained
re-renders (a component using countAtom ignores nameAtom changes)
✓ Fine-grained re-renders by default (subscribe to exactly the atoms you use)
✓ No selector boilerplate; derived state is just another atom
✓ Solves Context's "re-render everything" problem
✓ Great for state that's naturally decomposed into many independent pieces
✗ Many atoms can be harder to organize/trace than one centralized store
✗ Less rigid structure than Redux (a pro or con depending on the team)
原子模型是一种不同的、越来越流行的全局状态方法,它颠倒了 Redux 的自上而下结构:与其对大型存储进行分片,不如自下而上组合小型原子。
其内置的粒度在没有选择器的情况下提供了高效、有针对性的重新渲染 — 直接解决了 Context 的性能问题。
理解原子(和派生原子)完善了你对状态管理设计空间的认识,与单存储(Redux/Zustand)和响应式(MobX/Signals)模型并列,帮助你选择最适合应用程序状态形状的范式。