Atomic state

Jotai atoms, derived and async atoms.

Builds on Build a store.

The stores in the last two chapters are top-down: one state object, and every component carves out its slice with a selector. Redux Toolkit and Zustand both work this way, and both inherit the selector stability rules from chapter 33.

Atomic state turns that around. Instead of one big object, state is many tiny independent units called atoms. A component subscribes to exactly the atoms it reads, and derived values are atoms too, computed from other atoms with dependencies tracked automatically. There are no selectors to write and no slice to carve, because the atom is the slice. This chapter teaches the model with Jotai 3.0, the version in the sandbox, and covers Recoil, the library that popularized the idea, as history.

The problem: state that's naturally many small pieces#

Some UIs are made of many independent items: cells in a spreadsheet, nodes on a diagram canvas, rows with their own expanded state, widgets on a dashboard. Each item changes on its own, often frequently.

Lift that state into one parent and every change re-renders every item. Click any cell below and watch every render count go up.

Lifted state: one change, every cell renders
import { useState } from "react";
import { useRenderCount } from "guide-tools";

function Cell({ value, onInc }: { value: number; onInc: () => void }) {
  const renders = useRenderCount();
  return (
    <button onClick={onInc} style={{ width: 92 }}>
      {value} <small style={{ color: "#a8a29e" }}>r{renders}</small>
    </button>
  );
}

export default function App() {
  const [cells, setCells] = useState(() => Array<number>(12).fill(0));
  return (
    <div style={{ display: "grid", gridTemplateColumns: "repeat(4, 96px)", gap: 4 }}>
      {cells.map((value, i) => (
        <Cell key={i} value={value} onInc={() => setCells((cs) => cs.map((x, j) => (j === i ? x + 1 : x)))} />
      ))}
    </div>
  );
}

You can fix this with memo and stable callbacks, or with a store and a per-cell selector like (s) => s.cells[i]. Both work. But notice the shape of the fix: you keep a big structure and then work to give each item its own subscription. Atoms start from the other end. Each cell gets its own little piece of state, and components subscribe to the pieces they use.

One atom per cell
import { atom, useAtom, type PrimitiveAtom } from "jotai";
import { useRenderCount } from "guide-tools";

// Twelve independent atoms, created once at module level.
const cellAtoms = Array.from({ length: 12 }, () => atom(0));

function Cell({ cellAtom }: { cellAtom: PrimitiveAtom<number> }) {
  const [value, setValue] = useAtom(cellAtom);
  const renders = useRenderCount();
  return (
    <button onClick={() => setValue((v) => v + 1)} style={{ width: 92 }}>
      {value} <small style={{ color: "#a8a29e" }}>r{renders}</small>
    </button>
  );
}

export default function App() {
  return (
    <div style={{ display: "grid", gridTemplateColumns: "repeat(4, 96px)", gap: 4 }}>
      {cellAtoms.map((a, i) => (
        <Cell key={i} cellAtom={a} />
      ))}
    </div>
  );
}

Only the clicked cell re-renders, and nothing in the code was written to make that happen. That's the core appeal of atomic state: the granularity of subscription follows the granularity of the state.

Atoms are keys, the store holds values#

The most important thing to understand about Jotai is that an atom doesn't hold a value. atom(0) returns a small config object: "a piece of state whose initial value is 0". The value lives in a store, in a WeakMap keyed by that config object. Use the same atom with two different stores and you get two independent values.

That's why atoms are declared at module level (or memoized): the atom object's identity is the key. Create one inside a component body and you get a new key, and therefore fresh state, on every render. One of the exercises below is exactly that bug.

In terms of the toy store from chapter 33:

Toy storeJotai
one createStore(initial) with one state objectone store holding many atoms (createStore(), or a default store)
getState()store.get(atom)
setState(partial)store.set(atom, value)
subscribe(listener) for any changestore.sub(atom, listener) for one atom
useStore(store, selector)useAtomValue(atom): the atom is the selector
a context holding the store<Provider store={...}>, optional

So Jotai is still an external store with subscriptions. The difference is that subscriptions are per atom, and the store knows the dependency graph between atoms, so it only recomputes and notifies what actually depends on a change.

Primitive atoms and the hooks#

A primitive atom holds a value you set directly: atom(initialValue). Three hooks read and write it:

  • useAtom(atom) returns [value, setValue], like useState.
  • useAtomValue(atom) returns just the value.
  • useSetAtom(atom) returns just the setter, and doesn't subscribe: the component won't re-render when the atom changes. Use it for buttons and handlers that only write.

Here's the reading list as atoms. Watch which boxes flash.

The reading list in atoms
import { useAtom, useAtomValue, useSetAtom } from "jotai";
import { Rendered } from "guide-tools";
import { filterAtom, toggleReadAtom, unreadCountAtom, visibleBooksAtom } from "./atoms";

function UnreadBadge() {
  const unread = useAtomValue(unreadCountAtom);
  return <Rendered label="UnreadBadge">Unread: {unread}</Rendered>;
}

function FilterBox() {
  const [filter, setFilter] = useAtom(filterAtom);
  return (
    <Rendered label="FilterBox">
      <input placeholder="Filter" value={filter} onChange={(e) => setFilter(e.target.value)} />
    </Rendered>
  );
}

function BookList() {
  const visible = useAtomValue(visibleBooksAtom);
  const toggleRead = useSetAtom(toggleReadAtom); // writes only, never re-renders for it
  return (
    <Rendered label="BookList">
      {visible.map((b) => (
        <label key={b.id} style={{ display: "block" }}>
          <input type="checkbox" checked={b.read} onChange={() => toggleRead(b.id)} /> {b.title}
        </label>
      ))}
    </Rendered>
  );
}

export default function App() {
  return (
    <>
      <UnreadBadge />
      <FilterBox />
      <BookList />
    </>
  );
}

No provider: without one, Jotai uses a default store, a module-level singleton (getDefaultStore()), which is fine in a client-only app. Type in the filter and UnreadBadge stays still; toggle a book and FilterBox stays still.

Derived atoms and the dependency graph#

A derived atom is atom(read), where read receives a get function. Every get(otherAtom) call is recorded as a dependency. When any dependency changes, the store recomputes the derived atom, and if the new value differs (by Object.is) from the old one, it notifies the atom's subscribers.

An atom dependency graph
PRIMITIVE ATOMSbooksAtomfilterAtomDERIVED ATOMSunreadCountAtomvisibleBooksAtomCOMPONENTSUnreadBadgeBookListFilterBoxget()
Step 1 of 5

Two primitive atoms hold state. Two derived atoms read them with get(), and Jotai records each get() call as a dependency. Three components each read one atom.

Three properties fall out of this, and each is something you had to do by hand with a top-down store:

  • No selector boilerplate. visibleBooksAtom is the memoized selector. It recomputes only when booksAtom or filterAtom changes, and every component reading it shares one cached result, the way createSelector does in Redux.
  • Dependencies are dynamic. They're whatever get was called on during the last computation. A derived atom like atom((get) => (get(showArchivedAtom) ? get(archivedAtom) : get(activeAtom))) depends on archivedAtom only while showArchivedAtom is true.
  • Lazy evaluation. A derived atom is computed when something reads it. Nobody reading it means no work.

Write paths come in two more flavors:

  • Write-only atoms, atom(null, (get, set, ...args) => {...}), are actions. They can read any atoms and set any others, so they're where multi-atom updates live, like toggleReadAtom above.
  • Read-write derived atoms, atom(read, write), expose a computed value and a custom setter, for example an atom that reads a celsiusAtom as Fahrenheit and converts when written.

Async atoms and Suspense#

A derived atom's read can be async. Then its value is a promise, and useAtomValue (and useAtom) suspend until it resolves: in Jotai 3 they pass the promise to React's use(), so the nearest <Suspense> boundary shows its fallback, exactly as in the Suspense chapter. A rejection throws to the nearest error boundary.

read also receives an AbortSignal in its second argument. When a dependency changes while a fetch is in flight, the store aborts the stale computation, so you can cancel the request.

An async atom that depends on another atom
import { Suspense, useTransition } from "react";
import { atom, useAtomValue, useSetAtom } from "jotai";
import { fakeFetch } from "guide-tools";

type Book = { id: number; title: string; author: string; year: number };

const bookIdAtom = atom(1);

// Re-runs whenever bookIdAtom changes; the previous request is aborted.
const bookAtom = atom(async (get, { signal }) => {
  const id = get(bookIdAtom);
  const book: Book = await fakeFetch(`/books/${id}`, { signal, delay: 700 });
  return book;
});

function BookDetails() {
  const book = useAtomValue(bookAtom); // suspends while the promise is pending
  return (
    <p>
      <strong>{book.title}</strong> by {book.author} ({book.year})
    </p>
  );
}

function Picker() {
  const setId = useSetAtom(bookIdAtom);
  const [isPending, startTransition] = useTransition();
  return (
    <p>
      Plain set:{" "}
      {[1, 2, 3].map((id) => (
        <button key={id} onClick={() => setId(id)}>
          Book {id}
        </button>
      ))}
      <br />
      In a transition:{" "}
      {[4, 5, 6].map((id) => (
        <button key={id} onClick={() => startTransition(() => setId(id))}>
          Book {id}
        </button>
      ))}
      {isPending && " loading..."}
    </p>
  );
}

export default function App() {
  return (
    <>
      <Picker />
      <Suspense fallback={<p>Loading the book...</p>}>
        <BookDetails />
      </Suspense>
    </>
  );
}

A plain set replaces the details with the fallback while the new book loads. Setting the atom inside startTransition keeps the old details on screen until the new ones are ready, because the re-render is a transition and React won't hide already-visible content for it. That's the transitions behavior, working through an external store.

That last point is a real design difference from chapter 33. Jotai's default useAtomValue doesn't use useSyncExternalStore: it subscribes with store.sub in an effect and re-renders through useReducer, which is what lets atom updates take part in transitions and Suspense. The cost is the tearing guarantee. Jotai 3 makes the choice explicit with two lower-level hooks:

  • useAtomValueRaw(atom) never suspends: for an async atom it returns the promise itself.
  • useAtomValueRawSync(atom) is built on useSyncExternalStore, so it gets the chapter 33 guarantee (no tearing), at the cost of concurrent rendering for that value: its updates are always blocking. Like the other raw hook, it hands you the promise for an async atom instead of suspending.

If you'd rather show a loading state inline than suspend, wrap the async atom with unwrap from jotai/utils: unwrap(bookAtom, (prev) => prev ?? null) gives a synchronous atom that holds the fallback (here, the previous value) while the promise is pending. In Jotai 2 this was often done with loadable, which v3 removed in favor of unwrap.

Utilities you'll meet#

jotai/utils holds helpers built from the same primitives:

  • atomWithStorage(key, initialValue) persists to localStorage (or a storage you pass) and syncs across tabs.
  • atomWithReset and RESET for resettable atoms, atomWithDefault for an atom that's derived until it's set.
  • atomWithRefresh for an async atom you can re-run on demand, atomWithObservable for RxJS-style sources.
  • splitAtom(listAtom) turns an array atom into an atom of per-item atoms, so each row can subscribe to its own item.
  • useHydrateAtoms sets initial values from props, typically server data in SSR.

atomFamily moved out in v3#

A common need is "one atom per id": a book's expanded state, a cell by coordinates. Jotai 2 had atomFamily in jotai/utils. Jotai 3 removed it; the same API now lives in the separate jotai-family package (along with a newer atomTree helper for path-keyed atoms):

import { atom } from "jotai";
import { atomFamily } from "jotai-family"; // v2: from "jotai/utils"

const expandedFamily = atomFamily((id: number) => atom(false));

// expandedFamily(3) returns the same atom every time for id 3.
// The family is a Map from param to atom, so remove what you no longer need:
expandedFamily.remove(3);

The family is just a cache from parameter to atom. It never forgets on its own, so with an unbounded set of ids it leaks memory unless you call remove or configure setShouldRemove. When the set of items is known up front, a plain array of atoms or splitAtom is often simpler, and inside one component, useMemo(() => atom(...), [id]) gives a stable per-instance atom.

Providers and stores#

<Provider> scopes atoms: inside a provider, every atom has its own values, separate from the default store and from other providers. You can also create a store yourself and use it from outside React.

Stores and providers
import { atom, createStore, Provider, useAtom } from "jotai";

const countAtom = atom(0);

// A store created outside React. Same atom, independent value.
const storeA = createStore();
storeA.set(countAtom, 100);
storeA.sub(countAtom, () => console.log("storeA count is now", storeA.get(countAtom)));

function Counter({ label }: { label: string }) {
  const [count, setCount] = useAtom(countAtom);
  return (
    <p>
      {label}: <button onClick={() => setCount((c) => c + 1)}>{count}</button>
    </p>
  );
}

export default function App() {
  return (
    <>
      <Counter label="No provider (default store)" />
      <Provider store={storeA}>
        <Counter label="Provider with storeA" />
        <Counter label="Also storeA" />
      </Provider>
      <Provider>
        <Counter label="Provider with its own store" />
      </Provider>
      <button onClick={() => storeA.set(countAtom, (c) => c + 10)}>storeA.set from outside React</button>
    </>
  );
}
Nothing logged yet.

Uses for providers: isolating state per subtree (two independent editors on one page), giving each test a fresh store, and server rendering, where, as with every store in this part, a module-level default store would be shared across requests. In SSR apps, wrap the tree in a <Provider> so each request gets its own store, and seed it with useHydrateAtoms.

Recoil, as history#

Jotai's model comes from Recoil, which Meta open-sourced in 2020. Recoil introduced the vocabulary to React: atoms as shared units of state, selectors as derived (and async) state with automatic dependency tracking, atomFamily and selectorFamily for parameterized state, and Suspense integration. Its atoms needed globally unique string keys (atom({ key: "filter", default: "" })), and it needed a <RecoilRoot> around the app.

Recoil never reached 1.0, its development slowed, and it didn't keep up with React 18 and 19. Meta archived the GitHub repository on January 1, 2025, making it read-only. If you meet Recoil in an interview, it's usually in a migration question, and Jotai is the usual answer: the concepts map almost one to one (Recoil atom to Jotai primitive atom, selector to derived atom, useRecoilState to useAtom, useRecoilValue to useAtomValue, atomFamily to jotai-family), with object identity replacing string keys and no root required.

Top-down or bottom-up?#

One store with selectors (Redux, Zustand)Atoms (Jotai)
Shapeone object, carved by selectorsmany small atoms, composed by derivation
Re-render precisionas good as your selectorsper atom, automatic
Derived dataselectors, memoized by hand where neededderived atoms, cached and shared by default
Asyncthunks, or a separate server-cache toolasync atoms with Suspense built in
Global viewone state tree, easy to log and inspecta graph, harder to see as a whole
Actionscentralized (reducers, store actions)write-only atoms anywhere
Best forapp-wide state with clear ownershipmany independent pieces, heavy derivation, editors and canvases

Atoms shine when state is naturally granular and derivation-heavy. A single store shines when you want one inspectable tree and a central place where changes happen. The risk with atoms is the flip side of their freedom: with dozens of atoms across files, it can be hard to see what the state of the app is, and write logic can scatter. Keep atoms that belong together in one module and put multi-atom updates in write-only atoms.

Pitfalls#

Check your understanding#

Fix itThe counter that won't count

Clicking the button should count up, but it stays at 0. Fix it.

import { atom, useAtom } from "jotai";

function Counter() {
  const countAtom = atom(0);
  const [count, setCount] = useAtom(countAtom);
  return <button onClick={() => setCount((c) => c + 1)}>Count: {count}</button>;
}

export default function App() {
  return <Counter />;
}
Build itA derived count and a toggle action

In atoms.ts, implement unreadCountAtom as a derived atom and toggleReadAtom as a write-only atom. The checks use Jotai's default store directly (getDefaultStore()), the same store the app uses since there's no provider.

import { atom } from "jotai";

export type Book = { id: number; title: string; read: boolean };

export const booksAtom = atom<Book[]>([
  { id: 1, title: "Refactoring", read: true },
  { id: 2, title: "SICP", read: false },
  { id: 3, title: "Crafting Interpreters", read: false },
]);

// TODO: derive the number of unread books from booksAtom.
export const unreadCountAtom = atom((get) => 0);

// TODO: a write-only atom that flips `read` on the book with this id,
// producing a new array (don't mutate).
export const toggleReadAtom = atom(null, (get, set, id: number) => {});
PredictHow often does it compute?

Two components both read doubledAtom. The user clicks +1 once. How many times is "computing" logged in total, from first render through the click?

const countAtom = atom(1);
const doubledAtom = atom((get) => {
  console.log("computing");
  return get(countAtom) * 2;
});

function A() { return <p>{useAtomValue(doubledAtom)}</p>; }
function B() { return <p>{useAtomValue(doubledAtom)}</p>; }

export default function App() {
  const setCount = useSetAtom(countAtom);
  return (
    <>
      <A />
      <B />
      <button onClick={() => setCount((c) => c + 1)}>+1</button>
    </>
  );
}
Check your prediction
import { atom, useAtomValue, useSetAtom } from "jotai";

const countAtom = atom(1);
const doubledAtom = atom((get) => {
  console.log("computing");
  return get(countAtom) * 2;
});

function A() {
  return <p>A: {useAtomValue(doubledAtom)}</p>;
}
function B() {
  return <p>B: {useAtomValue(doubledAtom)}</p>;
}

export default function App() {
  const setCount = useSetAtom(countAtom);
  return (
    <>
      <A />
      <B />
      <button onClick={() => setCount((c) => c + 1)}>+1</button>
    </>
  );
}
Nothing logged yet.
Quick checkUpgrading to Jotai 3

After upgrading to Jotai 3, import { atomFamily } from 'jotai/utils' fails. What happened?

Explain it out loudAtoms versus a single store

An interviewer asks: "What's atomic state management, and when would you choose Jotai over Zustand or Redux?"

Interview angle

Say it in 30 seconds

Atomic state builds shared state bottom-up from small atoms instead of one store object. An atom is a key; its value lives in a store, and each component subscribes to the atoms it reads, so re-renders follow the granularity of the state with no selectors. Derived atoms compute from other atoms with get, and the store tracks those dependencies, caches results and recomputes lazily. Async atoms suspend through React's use and abort stale work. Write-only atoms act as actions. Jotai is the main library now; Recoil introduced the model but Meta archived it in January 2025. Atoms suit granular, derivation-heavy state; a single store suits one inspectable tree.

What is an atom in Jotai, and where does its value live?

basic

How do derived atoms work, and how do they compare with selectors in Redux?

intermediate

How do async atoms interact with Suspense and transitions?

intermediate

When would you choose atoms over a single store like Zustand or Redux?

senior

Does Jotai use useSyncExternalStore? What's the trade-off?

senior

A codebase still uses Recoil. What's its status, and how would you migrate?

intermediate

Recap#

  • Atomic state is bottom-up: many small atoms instead of one store, with subscriptions per atom, so re-render precision follows state granularity without selectors.
  • An atom is a key; its value lives in a store. Define atoms at module level, because identity is what links an atom to its state.
  • Derived atoms track dependencies through get, cache their value and recompute lazily; write-only atoms are actions that can update several atoms.
  • Async atoms suspend through React's use(), abort stale work via signal, and play well with transitions; unwrap gives inline loading states, and useAtomValueRawSync trades concurrency for useSyncExternalStore consistency.
  • Jotai 3 moved atomFamily to jotai-family and replaced loadable with unwrap. Use <Provider> for scoped and per-request stores. Recoil, which introduced the model, was archived by Meta on January 1, 2025.

Sources#