Reading and Writing Atoms with useAtom
You'll learn: How to read and update Jotai atoms using the useAtom hook, which works just like useState but for globally accessible state.
The Familiar Interface
Once you've created an atom with atom(), you need a way to actually use it in your components. This is where useAtom comes in. The beautiful part? It returns a tuple exactly like useState:
const [value, setValue] = useAtom(myAtom);
The first element is the current value, the second is a setter function. If you know useState, you already know useAtom.
The Key Difference: Global Scope
While the syntax mirrors useState, the behavior is fundamentally different. When you call useAtom(myAtom) in one component and useAtom(myAtom) in another component across your tree, they're reading and writing the same piece of state. No provider wrapping required. No prop drilling. No context boilerplate.
import { atom } from 'jotai';
import { useAtom } from 'jotai';
const countAtom = atom(0);
function Counter() {
const [count, setCount] = useAtom(countAtom);
return <button onClick={() => setCount(count + 1)}>{count}</button>;
}
function Display() {
const [count] = useAtom(countAtom); // same atom, same value
return <div>Count is: {count}</div>;
}
Both components stay in sync automatically. When Counter updates the atom, Display re-renders with the new value.
Analogy: Shared Notebook
Think of each atom as a specific page in a shared notebook. useAtom is like opening that notebook to the exact page and getting both a view of what's written there and a pencil to update it. Everyone with access to that page sees the same content instantly.
Key Takeaway: useAtom gives you [value, setter] just like useState, but the state is globally accessible wherever that atom is used—no providers, no drilling, just direct access.