Sub topic 4
Updating state with set and actions
This chapter assumes you can write React function components with hooks, you know TypeScript basics, and you understand immutable updates (copying an object instead of changing it). You should also have created a store with create, as covered in the previous chapters.
What an action is
A Zustand store holds two kinds of things: data and functions that change that data. The functions are called actions. They live inside the store object, next to the values they update.
Every action changes state through set. The create function passes set to your state creator, and set is the only supported way to write state from inside the store.
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 }),
}))The store has one value (count) and two actions (increment and reset). Components call actions directly, so you do not need action types or dispatch functions.
How set merges state
set takes a partial object and merges it into the current state. The merge is shallow. Zustand copies the top-level fields of the new object over the old ones, and it leaves other top-level fields alone.
import { create } from 'zustand'
interface ProfileState {
name: string
age: number
rename: (name: string) => void
}
const useProfileStore = create<ProfileState>()((set) => ({
name: 'Ada',
age: 36,
rename: (name) => set({ name }),
}))
useProfileStore.getState().rename('Grace')
console.log(useProfileStore.getState())
// { name: 'Grace', age: 36, rename: [Function] }age and rename survive because set({ name }) only replaces name. Actions are ordinary fields of the state object, so they are preserved by the merge as well.
The merge applies to the top level only. If a field holds a nested object, set replaces that whole object. You must copy the nested parts yourself:
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 } })),
}))If you wrote set({ settings: { theme } }), fontSize would disappear. TypeScript catches this one, because the object no longer matches the type. In plain JavaScript it fails silently.
Direct and functional updates
set accepts two forms.
| Form | Example | Use when |
|---|---|---|
| Object | `set({ count: 0 })` | The new value does not depend on the old state |
| Function | `set((state) => ({ count: state.count + 1 }))` | The new value is computed from the current state |
Prefer the function form whenever you read the current state. The function receives the latest state at the moment set runs. If you read a value earlier in the action and use it later, it can be stale, especially across an await.
// Risky: `count` may be out of date by the time set runs
const { count } = get()
await somethingSlow()
set({ count: count + 1 })
// Safe: reads the state at the moment of the update
await somethingSlow()
set((state) => ({ count: state.count + 1 }))Reading state inside an action with get
Sometimes an action needs to read state without updating it, or it needs to read first and then decide what to do. The state creator receives a second argument, get, which returns the current state.
import { create } from 'zustand'
interface CartState {
items: string[]
addItem: (item: string) => void
logCount: () => void
}
export const useCartStore = create<CartState>()((set, get) => ({
items: [],
addItem: (item) => {
if (get().items.includes(item)) return
set((state) => ({ items: [...state.items, item] }))
},
logCount: () => console.log(`Items in cart: ${get().items.length}`),
}))The addItem action returns early for duplicates, so set is never called and no component re-renders.
One action can also call another through get(), for example get().addItem('book').
Immutability and why mutation fails
Zustand decides whether state changed by comparing references. If you mutate an array or object in place and pass the same reference to set, the comparison sees no change and subscribers do not update.
// Wrong: pushes into the existing array, then sets the same reference
addItem: (item) =>
set((state) => {
state.items.push(item)
return { items: state.items }
}),
// Right: builds a new array
addItem: (item) =>
set((state) => ({ items: [...state.items, item] })),The wrong version may even change the data, but components that selected items will not re-render, because Object.is(oldItems, newItems) is true. Always return new arrays and objects. For deeply nested state, the immer middleware lets you write mutation-style code safely. A later chapter covers it.
Common immutable patterns:
- Add to an array:
[...state.items, item] - Remove from an array:
state.items.filter((i) => i.id !== id) - Update one array element:
state.items.map((i) => (i.id === id ? { ...i, done: true } : i)) - Update a nested object:
{ ...state.settings, theme }
Replacing state with the replace flag
set takes an optional second argument. When it is true, Zustand replaces the whole state instead of merging.
useCounterStore.setState({ count: 5 }, true)After this call the increment and reset actions are gone, because the new state object contains only count. TypeScript flags this when the object is missing required fields. Use replacement only when you pass a full state object, such as resetting a store to a saved initial state.
What happens when set runs
The following diagram shows the path of one update.
Two details matter here. First, set is synchronous: when it returns, the state has already changed, and get() immediately returns the new value. Second, Zustand skips the update entirely when the next state is identical to the current one by Object.is. set((state) => state) does nothing.
Calling actions from components
Components should select the action, not the whole store. Actions never change identity (they are created once), so selecting an action never triggers a re-render.
import { useCounterStore } from './counterStore'
function Controls() {
const increment = useCounterStore((state) => state.increment)
const reset = useCounterStore((state) => state.reset)
return (
<div>
<button onClick={increment}>Add one</button>
<button onClick={reset}>Reset</button>
</div>
)
}A component that only selects actions never re-renders because of store changes.
Common errors
- Mutating state and calling
setwith the same reference. The UI does not update. Return new objects and arrays. - Losing nested fields. Because the merge is shallow, forgetting
...state.settingsdrops sibling fields. - Using stale values. Read state through the function form of
setor throughget()right before you write. - Passing the replace flag by accident.
set(newState, true)removes any field you omit, including actions. - Putting side effects inside the updater function. The function passed to
setshould only compute the next state. Do the logging, network calls, and other side effects in the action body.
Exercises
Exercise
A store has todos: { id: number; done: boolean }[]. Write the body of an action toggle(id) that flips done for one todo without mutating the array, using the functional form of set.
Show answer
toggle: (id) => set((state) => ({ todos: state.todos.map((t) => (t.id === id ? { ...t, done: !t.done } : t)) })). The map call returns a new array, and the matching todo is replaced with a copy, so selectors that read todos see a new reference and re-render.
Exercise
A store has user: { name: string; email: string } and you call set({ user: { name: 'Sam' } }). What happens to email, and how do you fix the call?
Show answer
email is lost, because set merges only top-level fields and replaces the whole user object. Fix it by spreading the old object: set((state) => ({ user: { ...state.user, name: 'Sam' } })).