Skip to main content

Overview

Async atoms provide a first-class way to work with asynchronous data in TanStack Store. They automatically handle loading, success, and error states, making it easy to build robust applications that fetch and display remote data.

The createAsyncAtom API

The createAsyncAtom function creates a read-only atom that manages asynchronous operations. It returns a special state object that represents the current status of the async operation.

Async State Structure

Async atoms use a discriminated union type for their state, making it type-safe and easy to handle different states:

Working with Async States

Handling Loading State

When an async atom is first accessed, it starts in the pending state:

Handling Success State

Once the promise resolves, the atom transitions to the done state with the returned data:

Handling Error State

If the promise rejects, the atom transitions to the error state:

Real-World Examples

Basic Data Fetching

Async Atom with UI Components

Combining Async Atoms with Derived Stores

You can derive computed values from async atoms:

Error Handling with Custom Error Types

Best Practices

Async atoms are read-only. Once created, you cannot manually update their state. To refresh data, create a new async atom or use a regular atom with manual state management.

Pattern: Loading Indicators

Always provide feedback during loading states:

Pattern: Retry Logic

Implement retry logic by recreating the async atom:
For more complex async state management with features like caching, refetching, and mutations, consider using TanStack Query alongside TanStack Store.

How It Works Internally

Async atoms work by:
  1. Starting in the pending state when created
  2. Executing the async function immediately
  3. Using the reactive system to propagate state changes when the promise settles
  4. Automatically notifying subscribers when transitioning between states
The implementation leverages TanStack Store’s reactive core (based on alien-signals) to ensure efficient updates with minimal recomputations.

Next Steps