Non-component updates
A utility, service, or event handler needs to change Zustand state outside a React component.
Zustand · Const
Zustand action creators are functions that update a store, either colocated with state or exported separately at module level. External creators can be called without a hook and can facilitate code splitting.
Action creators can be colocated with a Zustand store or defined externally as exported functions. External creators call the store's setState API, allowing updates without requiring a React hook and supporting code splitting.
const action = (...args) => useBoundStore.setState(update)export const useBoundStore = create(() => ({
count: 0,
text: 'hello',
}))
export const inc = () =>
useBoundStore.setState((state) => ({ count: state.count + 1 }))
export const setText = (text: string) =>
useBoundStore.setState({ text })The store holds state while exported functions update it through the store API, so callers can invoke actions without using a hook.
A utility, service, or event handler needs to change Zustand state outside a React component.
A large application wants independently loadable update functions.
A store should expose its state transitions together with its data.
An action creator is an exported function that performs a store update, commonly by calling useBoundStore.setState. It can be invoked without a hook, unlike an action called through a component subscription.
Follow-up: When is this pattern especially useful? It is useful when actions should be callable outside React components and when code splitting is desirable.
The store can contain only state, while separate functions update it with setState. This separates the update functions from the state definition while retaining the same store instance.
Follow-up: How would you update from the current value? Pass an updater function to setState, such as state => ({ count: state.count + 1 }).
The documented alternative has two stated advantages: a hook is not required to call an action, and code splitting is facilitated. The trade-off is that colocated actions may feel more encapsulated.
Follow-up: What design choice does the documentation recommend? It recommends colocating actions and state, while presenting module-level functions as a valid alternative.
createsetStatePractice with no store actions