Course contentsShow
← React
Lesson 1720 of 2,39641. State Management EcosystemFree lesson

Creating Atoms with atom()

Using atom() to define primitive state atoms with initial values and optional read/write functions.

Creating Atoms with atom()

You'll learn how to define individual pieces of state in Jotai using the atom() function—the building block of Jotai's atomic state model.

What is an Atom?

In Jotai, an atom is the smallest unit of state. Think of atoms like tiny, independent containers that each hold one piece of data. Unlike a traditional store that bundles everything together, atoms let you create granular state pieces that components can subscribe to individually.

The atom() function creates these containers. At its simplest, you pass an initial value:

import { atom } from 'jotai';

const countAtom = atom(0);
const nameAtom = atom('Alice');
const todosAtom = atom([]);

Each atom is now a self-contained piece of state. Components that read countAtom won't re-render when nameAtom changes—this is the performance benefit of atomic granularity.

Beyond Primitives: Read and Write Functions

Atoms aren't limited to simple values. You can create derived atoms by passing a read function:

const doubleCountAtom = atom((get) => get(countAtom) * 2);

This atom automatically recomputes when countAtom changes. You can also define custom write behavior:

const incrementAtom = atom(
  (get) => get(countAtom), // read function
  (get, set) => set(countAtom, get(countAtom) + 1) // write function
);

Now you've encapsulated both the value and the action to modify it—all within the atom itself.

Why This Matters

Atoms eliminate boilerplate. No providers, no context setup—just define your state atoms and use them. The atom() function is declarative: you describe what the state is, and Jotai handles subscriptions and updates.

Key Takeaway: Use atom() to create primitive state containers with initial values, or add read/write functions to build derived state and custom actions—all in a single, composable unit.