Derived Atoms: Read-Only Computed State
You'll learn how to create atoms that automatically compute their values from other atoms, updating whenever their dependencies change.
The Core Idea
In Jotai, derived atoms are like formulas in a spreadsheet—they don't store their own data, but instead calculate their value from other atoms. You define them using a get function that reads other atoms, and Jotai handles all the dependency tracking automatically.
Think of it like this: if you have firstNameAtom and lastNameAtom, a derived atom can compute the full name without storing it separately. Whenever either name changes, the derived atom recalculates instantly.
Creating Derived Atoms
import { atom, useAtomValue } from 'jotai';
const firstNameAtom = atom('John');
const lastNameAtom = atom('Doe');
// Derived atom using get => get(otherAtom) syntax
const fullNameAtom = atom((get) => {
const first = get(firstNameAtom);
const last = get(lastNameAtom);
return `${first} ${last}`;
});
function Profile() {
const fullName = useAtomValue(fullNameAtom);
return <h1>{fullName}</h1>; // "John Doe"
}
The get function is your way to read other atoms. Jotai tracks which atoms you read, so when firstNameAtom or lastNameAtom updates, fullNameAtom automatically recomputes.
Read-Only Nature
Derived atoms are read-only by default—you can't directly set their value. They're purely computational, which keeps your state logic predictable and prevents inconsistencies.
const cartTotalAtom = atom((get) => {
const items = get(cartItemsAtom);
return items.reduce((sum, item) => sum + item.price, 0);
});
// Use with useAtomValue, not useAtom
const total = useAtomValue(cartTotalAtom);
Key Takeaway: Derived atoms compute values from other atoms using get => get(otherAtom) syntax, automatically updating when dependencies change—perfect for calculations, filtering, and transformations without storing redundant state.