Sub topic 7
Async actions and loading state
Earlier chapters showed how to update state with set and how to read it with selectors. This chapter covers actions that wait for something, such as a network request, and the loading and error state that goes with them.
This chapter assumes you know async/await, fetch, try/catch, and the basics of a Zustand store (create, set, selectors).
Zustand has no special async API
An async action is a normal function stored in the store. Zustand does not need thunks, sagas, or any other middleware for this. Inside the function you can await anything, and you call set whenever the state should change. A single async action usually calls set at least twice: once when work starts and once when it ends.
The state you track for a request usually has three parts:
- The data itself (
users). - A flag that says whether a request is running (
loading). - The last failure, if any (
error).
A complete fetch action
import { create } from 'zustand'
interface User {
id: number
name: string
}
interface UsersState {
users: User[]
loading: boolean
error: string | null
fetchUsers: () => Promise<void>
}
export const useUsersStore = create<UsersState>()((set) => ({
users: [],
loading: false,
error: null,
fetchUsers: async () => {
set({ loading: true, error: null })
try {
const response = await fetch('/api/users')
if (!response.ok) throw new Error(`Request failed: ${response.status}`)
const users: User[] = await response.json()
set({ users, loading: false })
} catch (e) {
set({ error: e instanceof Error ? e.message : 'Unknown error', loading: false })
}
},
}))The action runs in four steps:
set({ loading: true, error: null })runs first. It clears any old error, so a retry does not show a stale message.fetchruns. Afetchpromise only rejects on network failure, so the code checksresponse.okand throws for HTTP errors such as 404 or 500.- On success, one
setcall stores the data and turnsloadingoff together. - On failure, the
catchblock stores the message and also turnsloadingoff.
Each set call merges the object you pass into the existing state. Fields you leave out, such as fetchUsers itself, stay as they were.
The request lifecycle
The store has no field called "status" here. The state is spread across loading, error, and users. That is simple, but it allows combinations that make no sense, such as loading: true together with an error. The first set in the action prevents this by clearing the error. If you want the compiler to help, you can use one status field instead (see the next section).
Using the state in a component
Components subscribe to each field with its own selector, so each one re-renders only when its field changes.
import { useEffect } from 'react'
import { useUsersStore } from './usersStore'
function UserList() {
const users = useUsersStore((state) => state.users)
const loading = useUsersStore((state) => state.loading)
const error = useUsersStore((state) => state.error)
const fetchUsers = useUsersStore((state) => state.fetchUsers)
useEffect(() => {
fetchUsers()
}, [fetchUsers])
if (loading) return <p>Loading...</p>
if (error) return <p>Error: {error}</p>
return (
<ul>
{users.map((user) => (
<li key={user.id}>{user.name}</li>
))}
</ul>
)
}The action reference fetchUsers never changes after the store is created. That makes it safe in the useEffect dependency array, and the effect runs once on mount. In React development with Strict Mode, the effect runs twice, so the request fires twice. The next section covers a guard for that.
Edge cases
Overlapping requests
If a user clicks a refresh button twice, two requests run at once. Whichever response arrives last wins, even if it belongs to the older request. A simple guard is to skip the call while a request is already running. Read the current state with the second argument to the state creator, get:
import { create } from 'zustand'
interface User {
id: number
name: string
}
interface UsersState {
users: User[]
loading: boolean
error: string | null
fetchUsers: () => Promise<void>
}
export const useUsersStore = create<UsersState>()((set, get) => ({
users: [],
loading: false,
error: null,
fetchUsers: async () => {
if (get().loading) return
set({ loading: true, error: null })
try {
const response = await fetch('/api/users')
if (!response.ok) throw new Error(`Request failed: ${response.status}`)
const users: User[] = await response.json()
set({ users, loading: false })
} catch (e) {
set({ error: e instanceof Error ? e.message : 'Unknown error', loading: false })
}
},
}))get() returns the latest state at the moment you call it. Because set updates state synchronously, a second call made right after the first sees loading: true and returns early. This also removes the duplicate request from Strict Mode.
If the newest request should win instead, cancel the older one with an AbortController. Keep the controller in a module-level variable, since it is not state that components render.
Failures that never reach `catch`
Callers of fetchUsers() get a promise that always resolves, because the action catches its own errors. That is deliberate here. The error lives in the store and the UI reads it from there. If a caller needs to react to failure, for example to navigate away, rethrow inside catch or return a result value.
Updating after the component unmounts
The store is outside the component tree, so a response that arrives after unmount does not trigger a React warning. It just updates the store. This is usually what you want, since the data is available when the component mounts again.
Optimistic updates
For an action like "add item", you can update the state first and undo it if the request fails:
import { create } from 'zustand'
interface TodosState {
todos: string[]
addTodo: (title: string) => Promise<void>
}
export const useTodosStore = create<TodosState>()((set, get) => ({
todos: [],
addTodo: async (title) => {
const previous = get().todos
set({ todos: [...previous, title] })
try {
const response = await fetch('/api/todos', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ title }),
})
if (!response.ok) throw new Error(`Request failed: ${response.status}`)
} catch {
set({ todos: previous })
}
},
}))Saving previous before the update lets the rollback restore the exact earlier array. If other actions change todos while the request is pending, the rollback overwrites their changes, so use this pattern only when overlapping updates are unlikely.
Common mistakes
| Mistake | What happens | Fix |
|---|---|---|
| Forgetting `set({ loading: false })` in the `catch` block | The spinner never stops after an error | Reset `loading` in both the success and error paths |
| Not checking `response.ok` | HTTP errors such as 500 are treated as success and `json()` may fail | Throw when `response.ok` is false |
| Not clearing `error` when a request starts | The old error stays visible during a retry | Set `error: null` in the first `set` call |
| Calling `set` with the old state captured before an `await` | The update overwrites changes made while waiting | Use the functional form `set((state) => ...)` after the `await` |
Keeping it simple
Hand-written fetch actions work well for a few endpoints. If you need caching, background refetching, deduplication, or pagination, a server-state library such as TanStack Query handles those problems, and Zustand can keep the client-only state beside it. The later chapter on pitfalls returns to this decision.
Exercise
In the fetchUsers action, why does the catch block call set({ error: ..., loading: false }) and not only set the error? What would the user see if loading: false were left out?
Show answer
The loading flag was set to true at the start, and nothing else turns it off on failure. Without loading: false, the store would keep loading: true forever after a failed request, so a component that checks loading first would show "Loading..." and never reach the error message.
Exercise
Two components call fetchUsers() on mount at nearly the same time. Using the guarded version of the action, how many network requests are sent, and why?
Show answer
One. The first call runs set({ loading: true }) synchronously before its first await. The second call runs get().loading, sees true, and returns early, so only the first request is sent.