状態管理

Jotai派生Atom

既存の atom から新しい値を計算する3つのパターン

派生Atom(Derived Atom)とは?
他の atom の値から計算された atom

派生 Atom は、atom() のゲッター関数で他の atom の値を読み取り、計算結果を返します。 依存先の atom が変わると、自動的に再計算されます。

📖 読み取り専用

他の atom から計算した値を返すだけ

atom((get) => get(a) * 2)

✏️ 書き込み専用

複数の atom をまとめて更新するアクション

atom(null, (get, set) => ...)

🔄 読み書き可能

変換と逆変換の両方を定義

atom((get) => ..., (get, set, v) => ...)
料金計算(読み取り専用の派生Atom)
price × quantity + tax を派生Atom で自動計算
小計¥1,000
消費税(10%)¥100
合計¥1,100

読み取り専用 Atom の定義

const subtotalAtom = atom((get) => {
return get(priceAtom) * get(quantityAtom);
});
// ↑ priceAtom か quantityAtom が変わると自動再計算

書き込み専用 Atom(リセットアクション)

const resetCartAtom = atom(null, (_get, set) => {
set(priceAtom, 1000);
set(quantityAtom, 1);
});
// ↑ 複数の atom をまとめて更新
通貨変換
読み書き可能な派生Atom で双方向変換
const priceInDollarsAtom = atom(
(get) => get(priceAtom) / 150, // 読み取り
(_get, set, usd) => { // 書き込み
set(priceAtom, usd * 150);
}
);
温度変換
摂氏と華氏を双方向で変換

どちらの入力を変更しても、もう一方が自動で更新されます。 これが「読み書き可能な派生Atom」の力です。

const fahrenheitAtom = atom(
(get) => get(celsiusAtom) * 9/5 + 32,
(_get, set, f) => {
set(celsiusAtom, (f - 32) * 5/9);
}
);
派生Atom まとめ
3つのパターンの使い分け
パターン定義用途
読み取り専用atom((get) => ...)計算結果の表示、フィルタリング
書き込み専用atom(null, (get, set) => ...)リセット、一括更新などのアクション
読み書き可能atom((get) => ..., (get, set, v) => ...)双方向変換(通貨、単位など)
Next Steps
次のステップ

実践的な Todo アプリを作りながら、atomFamily や非同期処理など応用パターンを学びましょう。