External store updates
An event handler, service, or module needs to update a vanilla store without a React hook.
Zustand · Module
store.setState updates a Zustand store from external code. It supports partial or updater-based changes, shallow-merges object updates by default, and can replace the complete state when requested.
store.setState updates a Zustand store from outside React or the store's action definitions. It accepts a complete or partial value, or an updater function that receives the current state; by default it shallow-merges object updates, while replace: true replaces the entire state and requires a complete state value.
store.setState(partial, replace?)| Name | Type | Description |
|---|---|---|
partial | T | Partial<T> | ((state: T) => T | Partial<T>) | A complete state, a shallow partial state, or a function receiving the current state and returning either form. |
replace | false | undefined, or true for complete replacement | When true, replace the whole state instead of shallow-merging an object update; current v5 typing requires a complete state for replacement. |
void
setState rather than mutating the store directly.import { createStore } from 'zustand/vanilla'
type State = { count: number }
const store = createStore<State>(() => ({ count: 0 }))
const unsubscribe = store.subscribe((state) => {
console.log(state.count)
})
store.setState({ count: 1 })
store.setState((state) => ({ count: state.count + 1 }))
unsubscribe()Creates a vanilla store, applies a shallow partial update, then derives another update from the current state.
An event handler, service, or module needs to update a vanilla store without a React hook.
Actions are intentionally kept outside the store definition to support module organization or code splitting.
A primitive-valued store needs its current value changed directly.
store.setState update Zustand state?It accepts a partial or complete state value, or a function that derives one from the current state. The default behavior shallow-merges object updates and notifies subscribers.
Follow-up: What does the second argument do? replace: true switches from merging to full replacement, so the value must be a complete state.
Use store.setState({ key: value }) for a partial object update, or pass an updater such as store.setState(state => ({ count: state.count + 1 })). This makes external, module-level updates possible without calling a React hook.
Follow-up: When would direct assignment be appropriate? For primitive state, set the new primitive directly rather than wrapping it in an object.
The default operation is a shallow merge. With replace set to true, Zustand replaces the complete stored value instead.
Follow-up: Why can replace: true be dangerous? An incomplete replacement can remove unrelated state fields and is rejected by current TypeScript overloads when the state type requires more fields.
createStoresetgetStategetInitialStatesubscribe