Write-Only and Read-Write Atoms
What you'll learn: How to create Jotai atoms that perform custom logic or side effects when updated, enabling coordination between multiple atoms.
The Core Idea
So far, you've seen atoms that hold state and derived atoms that compute from other atoms. But Jotai also supports write-only atoms (atoms with no value, only a write function) and read-write atoms (atoms with both custom read and write logic). These allow you to encapsulate complex update patterns, coordinate multiple atoms, or trigger side effects when state changes.
Think of it like the difference between a simple property and a method. A basic atom is like name = "Alice". A write-only atom is like a reset() method—it doesn't hold a value, it just does something when called. A read-write atom is like a getter/setter pair with custom logic.
Write-Only Atoms
A write-only atom has null as its first argument (no read function) and a custom write function:
const incrementAgeAtom = atom(
null, // No value to read
(get, set) => {
const currentAge = get(ageAtom);
set(ageAtom, currentAge + 1);
}
);
// Usage:
const incrementAge = useSetAtom(incrementAgeAtom);
incrementAge(); // Increments ageAtom
Read-Write Atoms
Combine custom read and write logic in one atom:
const doubleCountAtom = atom(
(get) => get(countAtom) * 2, // Read: derived value
(get, set, newValue) => {
set(countAtom, newValue / 2); // Write: reverse the doubling
}
);
These atoms let you coordinate multiple atoms, validate updates, or trigger effects without polluting components with complex logic.
Key Takeaway: Write-only and read-write atoms in Jotai enable encapsulated actions and coordinated updates across multiple atoms, acting as composable state operations rather than just state containers.