Whole-state reset
Resetting a store to a known complete snapshot.
Zustand · Const
The replace flag is the second argument to Zustand’s set or setState functions. Set it to true to replace the entire store state instead of shallow-merging an update.
Zustand normally shallow-merges updates into the current state. Supplying true as the replace flag makes the update replace the entire state, so the supplied value must be a complete valid state object rather than a partial update.
set(partial, replace?)
setState(partial, replace?)| Name | Type | Description |
|---|---|---|
partial | T | Partial<T> | ((state: T) => T | Partial<T>) | The new state, a partial state, or a function producing state; with replacement enabled, it must be complete. |
replace | boolean | Whether to replace the complete state instead of shallow-merging the update. |
void
import { create } from 'zustand'
type Store = { bears: number }
const useBearStore = create<Store>(() => ({ bears: 0 }))
useBearStore.setState({ bears: 5 }, true)
console.log(useBearStore.getState())Pass true as the second argument to replace the entire store state.
Resetting a store to a known complete snapshot.
Replacing primitive or compound state with a newly constructed value.
Applying a function that computes the next complete state.
The replace flag is the second argument to set or setState. When true, Zustand replaces the whole state instead of performing its default shallow merge, so the value must represent the complete state.
Follow-up: What happens with setState({}, true)? It is rejected by the stricter TypeScript typing because the empty object cannot represent the complete state.
Use a partial update without the flag when changing selected properties. Pass true only when intentionally replacing the complete state object.
Follow-up: Why is replacement risky for nested data? Any nested data omitted from the replacement is discarded rather than retained by a merge.
A dynamic flag can be annotated by building the arguments as Parameters<typeof useBearStore.setState>, then spreading them into setState. This preserves the appropriate overload for the runtime boolean.
Follow-up: What must the replacement value contain when the runtime flag resolves to true? It must be a complete state object.
setsetStatecreateStoregetStategetInitialState