既存の atom から新しい値を計算する3つのパターン
派生 Atom は、atom() のゲッター関数で他の atom の値を読み取り、計算結果を返します。 依存先の atom が変わると、自動的に再計算されます。
他の atom から計算した値を返すだけ
atom((get) => get(a) * 2)複数の atom をまとめて更新するアクション
atom(null, (get, set) => ...)変換と逆変換の両方を定義
atom((get) => ..., (get, set, v) => ...)読み取り専用 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 をまとめて更新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((get) => ...) | 計算結果の表示、フィルタリング |
| 書き込み専用 | atom(null, (get, set) => ...) | リセット、一括更新などのアクション |
| 読み書き可能 | atom((get) => ..., (get, set, v) => ...) | 双方向変換(通貨、単位など) |
実践的な Todo アプリを作りながら、atomFamily や非同期処理など応用パターンを学びましょう。