Skip to main content

What is an Atom?

Atoms are the foundational building blocks of TanStack Store’s reactivity system. They are low-level primitives that provide fine-grained reactive state management with automatic dependency tracking. While Stores provide a simple, high-level API, atoms give you more control over reactivity, comparison logic, and performance optimization.

Creating Atoms

Use the createAtom function to create atoms. Like stores, atoms can be created from values or getter functions:

Mutable Atoms (from values)

Read-only Atoms (from functions)

Read-only atoms (computed atoms) automatically track their dependencies and recompute only when necessary.

Type Signatures

Atom API

set(valueOrUpdater)

Sets the atom’s value. Available only on mutable atoms (not read-only atoms).

get()

Returns the current value of the atom. Automatically tracks dependencies when called inside computed atoms or subscriptions.

subscribe(observerOrFn)

Subscribes to changes in the atom. Returns a subscription with an unsubscribe method.

Custom Comparison

By default, atoms use Object.is to determine if a value has changed. You can provide a custom comparison function:
Custom comparison functions are useful for avoiding unnecessary re-renders with complex objects or when you want to implement shallow equality.

Computed Atoms (Derived State)

Computed atoms automatically track dependencies and only recompute when their dependencies change:

Lazy Evaluation

Computed atoms are lazy - they only compute when their value is accessed:

Async Atoms

TanStack Store provides createAsyncAtom for handling asynchronous state:
The state type is:

Practical Examples

Shopping Cart

Form State with Validation

Filtering and Sorting

How Atoms Work Internally

Atoms use a reactive graph system with automatic dependency tracking:
  1. Dependency Tracking: When you call get() inside a computed atom or subscription, the atom automatically tracks that dependency
  2. Change Propagation: When a mutable atom changes via set(), it notifies all dependent atoms and subscriptions
  3. Dirty Checking: Computed atoms mark themselves as “dirty” and only recompute when accessed
  4. Efficient Updates: Only atoms that actually changed will trigger subscriber notifications
From atom.ts:151-156:

Atoms vs Stores

Atoms

  • Lower-level primitive
  • Custom comparison logic
  • More explicit API
  • Better for libraries
  • Direct control over reactivity

Stores

  • Higher-level abstraction
  • Simpler API
  • Better for applications
  • Built on top of atoms
  • Convenient state property

Stores

High-level API built on atoms

Derived Stores

Create computed state from multiple sources

Subscriptions

React to atom changes

Batching

Batch multiple atom updates