Partial object updates
Change selected properties while preserving other top-level state fields.
Zustand · Module
Zustand's setState updates a store from a partial value or updater function. It shallow-merges object updates by default, or replaces the entire state when replace is true.
The store's setState API accepts either a partial state value or an updater function. By default it shallow-merges object updates; passing true as the replace argument replaces the whole state, so use that mode carefully when existing data must be discarded.
store.setState(nextState, replace?)| Name | Type | Description |
|---|---|---|
nextState | State | Partial<State> | ((state: State) => State | Partial<State>) | A partial state value or updater function that returns the state update. |
replace | boolean | When true, replaces the complete state instead of performing the default shallow merge. |
The store API's setState method updates the state and notifies subscribed listeners; the method itself returns void.
import { createStore } from 'zustand/vanilla'
type Position = { x: number; y: number }
const positionStore = createStore<Position>(() => ({ x: 0, y: 0 }))
positionStore.setState({ x: 10, y: 20 })
console.log(positionStore.getState())
positionStore.setState({ x: 30, y: 40 }, true)
console.log(positionStore.getState())Creates a vanilla store, applies a shallow update, then replaces the entire state with the second argument set to true.
Change selected properties while preserving other top-level state fields.
Set a new primitive, object, or array value in a vanilla store.
Reset or overwrite every state field with a deliberately complete value.
setState updates the store and notifies its listeners. With an object update, Zustand performs a shallow merge by default, so unchanged top-level properties remain available.
Follow-up: What is the alternative when the state is a primitive or an array? Use direct assignment of the new value, and use replace=true when the new value must replace the complete state.
Pass true as the replace argument to replace the complete state instead of merging it. This is useful for full-state replacement but can remove existing nested data.
Follow-up: Why can replace=true be risky? Because it discards state that is not included in the replacement value, including nested data and potentially store actions.
For object or array state, create a new object or array rather than mutating the current value. Then pass that new value to setState so the store observes the update correctly.
Follow-up: How would you update one property based on the current state? Pass an updater function that receives the current state and returns the changed portion.
createStoregetStategetInitialStatesubscribeset