Sub topic 4
Updating state with set and actions
This chapter assumes you can write React function components with hooks, you know how to create a store with create, and you understand immutable updates (copying objects instead of changing them).
What set does
In Zustand, an action is a function stored in the store next to the data it changes. Actions call set to update state. set takes either a partial object or a function that returns one. Zustand merges the result into the existing state with a shallow merge, so fields you leave out stay as they were.
import { create } from 'zustand'
interface CounterState {
count: number
increment: () => void
reset: () => void
}
export const useCounterStore = create<CounterState>()((set) => ({
count: 0,
increment: () => set((state) => ({ count: state.count + 1 })),
reset: () => set({ count: 0 }),
}))reset passes an object, because the new value does not depend on the old one. increment passes a function, because the new value is based on the current count. The function receives the latest state, so it stays correct even when several updates happen in a row.
Merging is shallow
The merge only covers the top level. If a field holds a nested object, replacing it replaces the whole object. Spread the old value to keep its other fields.
import { create } from 'zustand'
interface SettingsState {
settings: { theme: string; fontSize: number }
setTheme: (theme: string) => void
}
export const useSettingsStore = create<SettingsState>()((set) => ({
settings: { theme: 'light', fontSize: 14 },
setTheme: (theme) =>
set((state) => ({ settings: { ...state.settings, theme } })),
}))Without ...state.settings, fontSize would be lost.
Replacing instead of merging
set accepts a second argument. When it is true, the state is replaced and not merged. This is rarely needed in application code, but tests use it to restore a store.
useCounterStore.setState({ count: 5 }, true)After this call, increment and reset are gone, because the new state did not include them. Only use replace with a full state object.
Reading state inside an action
An action sometimes needs the current state without changing it. The creator function receives get as its second argument.
import { create } from 'zustand'
interface CartState {
items: string[]
addUnique: (item: string) => void
}
export const useCartStore = create<CartState>()((set, get) => ({
items: [],
addUnique: (item) => {
if (get().items.includes(item)) return
set((state) => ({ items: [...state.items, item] }))
},
}))Common errors
| Mistake | Effect | Fix |
|---|---|---|
| Mutating state in place | No re-render | Return new objects and arrays |
| Forgetting to spread a nested object | Sibling fields disappear | Use `{ ...state.nested, key }` |
| Using `set({ count: get().count + 1 })` after an `await` | May use stale data | Use `set((state) => ...)` |
| Using `set(..., true)` with a partial object | Actions are removed | Pass the full state or omit `true` |
Exercise
A store has user: { name: string; email: string }. Write an action setName(name) that changes only the name and keeps the email. Why does set({ user: { name } }) break the store?
Show answer
Use setName: (name) => set((state) => ({ user: { ...state.user, name } })). The merge in set is shallow, so set({ user: { name } }) replaces the whole user object and email is lost.