Typed store construction
Define a typed store with state fields and action methods before passing it to create.
Zustand · Type Alias
StateCreator is the function type for defining Zustand store state and actions. It receives set, get, and store utilities and returns the state shape exposed by the store.
StateCreator is the type used for a Zustand store-creation function. The function receives set, get, and store utilities, then normally returns the state fields and actions that the store exposes; middleware can specialize the creator's mutator tuple.
StateCreator<T, Mis, Mos, U = T>| Name | Type | Description |
|---|---|---|
stateCreatorFn | StateCreator<T, [], []> | The store creator function; it receives set, get, and store and usually returns the exposed state and methods. |
A state creator function when used as the function type accepted by Zustand APIs; when passed to create, it produces a bound store hook with StoreApi utilities.
import { create } from 'zustand'
import type { StateCreator } from 'zustand'
type CounterState = {
count: number
increment: () => void
}
const counterCreator: StateCreator<CounterState> = (set) => ({
count: 0,
increment: () => set((state) => ({ count: state.count + 1 })),
})
const useCounter = create(counterCreator)
useCounter.getState().increment()
console.log(useCounter.getState().count)StateCreator types the function that supplies a store's state and actions; the creator receives Zustand's store utilities and returns the exposed state object.
Define a typed store with state fields and action methods before passing it to create.
Provide a creator to middleware such as persist, devtools, immer, or subscribeWithSelector.
Extract reusable state-and-action slices that can be combined into larger Zustand stores.
StateCreator describes a function that receives set, get, and store, and usually returns the state and methods exposed by the store. It is commonly supplied to create or a middleware wrapper.
Follow-up: How can middleware affect the type? Middleware can change the creator's mutator tuple, so the resulting StateCreator type may record middleware-specific mutators.
The first generic describes the store state. The remaining generic parameters describe mutators applied before and after the creator, while an optional fourth generic describes the returned slice or object shape.
Follow-up: Why can a middleware-wrapped creator have a different type? Its middleware augments or transforms the mutator tuples, allowing the resulting store API to reflect those additions.
A creator should return an object containing the state values and actions to expose. The set function can update state directly or from the previous state, while get and store provide access to store data and APIs.
Follow-up: When is synchronous access unsafe? During initialization, set, get, and store must not be called synchronously; defer such calls until an action runs after creation.
createcreateWithEqualityFnpersistdevtoolsimmersubscribeWithSelector