External updates
A module-level command needs to update Zustand state without rendering a component.
Zustand · Module
useStore.setState updates a Zustand store from outside React. It merges partial updates by default, or replaces the complete state when the second argument is true.
The store API method accepts either a partial state object or an updater function and merges that result by default. Passing true as the second argument switches to complete replacement, which requires supplying every part of the state.
useStore.setState(partial, replace?)| Name | Type | Description |
|---|---|---|
partial | T | Partial<T> | ((state: T) => T | Partial<T>) | A partial or complete state value, or a function receiving the current state and returning a partial or complete state value. |
replace | boolean | undefined | When true, replace the complete store state instead of merging the update; this requires a complete state value. |
void
import { create } from 'zustand'
type State = { count: number; text: string }
const useStore = create<State>(() => ({ count: 0, text: 'hello' }))
useStore.setState({ count: 1 })
useStore.setState((state) => ({ count: state.count + 1 }))
useStore.setState({ count: 10, text: 'replaced' }, true)
The first two calls merge partial updates; the final call replaces the complete store state.
A module-level command needs to update Zustand state without rendering a component.
Only one or a few fields should change while preserving the rest of the store.
A reset or scalar-store update must discard the previous state entirely.
setState support?setState accepts a partial value, a complete value, or a function that derives either from the current state. Without the replacement flag, the result is merged into the existing state.
Follow-up: What changes when replacement is enabled? Passing true makes the supplied value the complete state, so an incomplete object is invalid.
The second argument controls replacement. When it is true, Zustand replaces rather than merges the store state, and the supplied state must be complete.
Follow-up: Why can setState({}, true) be rejected? It would discard required state fields and produce an invalid state.
setState be used outside React components?The store API is available on the function returned by create, so updates can be issued outside a React component or hook call. Zustand then notifies listeners appropriately.
Follow-up: When would externally defined actions be useful? They can avoid needing a hook to invoke an action and can support code splitting.
creategetStategetInitialStatesubscribeset