External updates
Update a vanilla store from an event handler or other code outside the state creator.
Zustand · Type Alias
StoreApi.setState applies an external update to a Zustand store and notifies subscribers. By default, object updates are shallow-merged; pass true to replace the entire state.
setState is the store API for applying an update from outside the state creator. Pass either a new state value or an updater function; the optional replace flag controls whether the update replaces the complete state instead of using the default shallow merge.
store.setState(partial, replace?)| Name | Type | Description |
|---|---|---|
partial | T | Partial<T> | ((state: T) => T | Partial<T>) | The replacement state value or an updater function that derives the next state. |
replace | boolean | When true, replace the complete state; otherwise object updates use shallow merging. |
The page documents the store API and its behavior but does not specify a separate return value for setState; treat it as an update operation.
createStore exposes setState alongside the other store API utilities.replace false merges object updates rather than discarding unspecified properties.true when the new value must become the complete store state; otherwise existing object fields remain.import { createStore } from 'zustand/vanilla'
type Position = [number, number]
const positionStore = createStore<Position>()(() => [0, 0])
positionStore.setState([10, 20], true)
console.log(positionStore.getState())Creates a vanilla store containing an array, then replaces the entire state with a new position.
Update a vanilla store from an event handler or other code outside the state creator.
Replace an array, tuple, or primitive that is itself the store state.
Restore a complete known snapshot, such as during test cleanup.
Derive the next object state from the current value with an updater function.
setState updates a store through its public API and notifies subscribers of the change. Its first argument can be a value or an updater, while the optional replacement flag determines whether the whole state is replaced.
Follow-up: Why can replacing an object state be destructive? Because replacement removes properties not present in the supplied value; shallow merging preserves them.
The default behavior is a shallow merge for object-like state. Passing true as the second argument changes the operation to complete replacement.
Follow-up: How would you update an array state? Supply the new array and use replacement semantics when the array itself is the store state.
Updates should treat stored objects and arrays immutably: create a new object or array and pass it to the update API. This ensures the store receives a changed value rather than a mutation of existing state.
Follow-up: What should be done for a primitive state? Assign the new primitive directly, because object-merging semantics are not appropriate.
createStoresetgetStategetInitialStatesubscribeuseStore