Computed updates
A new value depends on the current value, such as incrementing a counter.
Zustand · Module
Zustand’s set function updates store state using a partial object or an updater function. It shallowly merges top-level fields by default, while a replacement flag can replace the entire state.
Zustand supplies set to the store initializer so actions can update state. Pass a partial object for direct changes or a function that receives the current state; updates are shallowly merged unless replacement is requested.
set(partial, replace?)| Name | Type | Description |
|---|---|---|
partial | object | (state) => object | A partial state object or updater function that returns the state update. |
replace | boolean | Optional flag that replaces the entire store state instead of shallowly merging it. |
The set function updates the store and notifies its listeners; the page does not specify a separate return value.
import { create } from 'zustand'
type Store = {
count: number
increment: () => void
reset: () => void
}
const useStore = create<Store>((set) => ({
count: 0,
increment: () => set((state) => ({ count: state.count + 1 })),
reset: () => set({ count: 0 }),
}))
export function Counter() {
const count = useStore((state) => state.count)
return <button onClick={useStore.getState().increment}>{count}</button>
}The store exposes actions that call set with either a partial object or an updater function.
A new value depends on the current value, such as incrementing a counter.
Only selected top-level fields need changing while the remaining store state stays intact.
A complete state object must replace the current store value.
A nested object needs modification without mutating the existing reference.
set updates the store and normally shallowly merges the supplied partial state into the existing state. It can receive either an object or an updater function that derives the update from current state.
Follow-up: How do you update a nested object safely? Create a new object for the changed level and spread the existing nested value so unrelated properties remain intact.
Use an updater function when the next value depends on current state, such as incrementing a counter. This form receives the current state and returns the partial update.
Follow-up: Why avoid mutating the current object? Zustand relies on immutable reference changes to detect updates and notify subscribers correctly.
By default, set merges only the top level. For a nested object, explicitly copy the nested object and return the updated copy.
Follow-up: What does set(state => newState, true) do? It replaces the complete store state instead of performing the default merge.
setStatecreategetimmutable state and mergingupdating state