State-dependent updates
A component needs to change a value based on its current value, such as incrementing a counter.
Zustand · Const
Zustand store actions are functions defined alongside state and used to update it through set. They avoid requiring dispatched actions and reducers for ordinary state changes.
An action in Zustand is a function kept in the store alongside state. It calls the provided set function with either a partial object or an updater function, allowing components or external code to trigger state changes without separate reducers or dispatched actions.
create((set) => ({ state, action: (...args) => set((state) => partialState) }))| Name | Type | Description |
|---|---|---|
stateCreatorFn | StateCreator<T, [], []> | A function receiving Zustand's set function and returning the store state and action properties. |
The store containing its state and exposed action functions; a created hook also exposes the store API for external access.
import { create } from 'zustand'
type Store = {
count: number
increment: (amount: number) => void
}
const useStore = create<Store>()((set) => ({
count: 0,
increment: (amount) => set((state) => ({ count: state.count + amount })),
}))
useStore.getState().increment(2)
console.log(useStore.getState().count)The action is stored beside the state and updates the count through Zustand's provided set function.
A component needs to change a value based on its current value, such as incrementing a counter.
State and its mutations should form one reusable store API.
An action should be callable without requiring a React hook, or code should be split across modules.
Actions are functions exposed as properties of the store, commonly defined beside the state in the create callback. They update state by calling the supplied set function with a partial state object or an updater function.
Follow-up: Can actions live outside the store? Yes. External functions can call useBoundStore.setState, which avoids requiring a hook and can support code splitting.
Zustand does not require dispatched actions or reducers for ordinary updates. An action can directly calculate the next partial state and pass it to set, keeping state transitions close to the data they modify.
Follow-up: When might a reducer-style design be useful? If Redux-like reducers are required, define a dispatch function at the store root or use the documented redux middleware.
A store action can use the updater form of set, receiving the current state and returning the changed fields. This is useful when the next value depends on the existing value, such as incrementing a counter.
Follow-up: How can an action be invoked without a React component? Read the store API with useStore.getState() and call the exposed action, or define a module-level function using setState.
setsetStatecreatecreateStorestore actionsselectorsredux middleware