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 thecreateAtom 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 useObject.is to determine if a value has changed. You can provide a custom comparison function:
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 providescreateAsyncAtom for handling asynchronous state:
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:- Dependency Tracking: When you call
get()inside a computed atom or subscription, the atom automatically tracks that dependency - Change Propagation: When a mutable atom changes via
set(), it notifies all dependent atoms and subscriptions - Dirty Checking: Computed atoms mark themselves as “dirty” and only recompute when accessed
- Efficient Updates: Only atoms that actually changed will trigger subscriber notifications
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
stateproperty
Related Concepts
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