Skip to content
masterclassBuddyTech Buzz5 fresh blogs · 5:00 AM IST

API reference

Zustand API reference

Zustand state management

Identifiers
108
With full guides
80
Types
6

Topics covered

  • Creating a store
  • Selectors
  • Slices pattern
  • persist middleware
  • Immer integration
  • Async actions
  • Avoiding re-renders
  • Testing stores

Function

NameWhat it does
createFunction
createStorecreateStore creates a vanilla Zustand store with an imperative API. Pass a state creator to define its state and actions.
persistThe persist middleware saves Zustand store state across page reloads or application restarts. It supports custom storage, selective persistence, version migration, merging, and controlled rehydration.
immerThe immer middleware lets Zustand updates use mutable-looking draft syntax while producing immutable state. Wrap a state creator with it to simplify nested updates.
subscribeWithSelectorsubscribeWithSelector adds selector-based subscriptions to a Zustand store. Listeners can react to changes in selected data instead of observing unrelated state updates.
combineZustand's combine middleware merges an initial state with a creator for additional state and actions. It automatically infers the resulting store types, avoiding an explicit state definition in common TypeScript usage.
devtoolsThe devtools middleware connects a Zustand store to the Redux DevTools Extension without Redux. It supports configuration for connection naming, environment-based enablement, action labels, and action filtering.
shallowshallow compares two values using top-level equality rules. It is useful for fast checks of simple objects and collections, but it does not recursively compare nested data.
createWithEqualityFncreateWithEqualityFn creates a React hook store like create, while allowing a default equality function. Equality checks give finer control over selector-driven re-renders.
reduxZustand's redux middleware builds a store from a reducer and initial state. It adds typed action dispatching while retaining Zustand's store APIs.
createJSONStorageCreates a Zustand persistence storage adapter around a custom storage engine. It serializes and parses persisted values as JSON, with optional replacer and reviver customization.
useShallowuseShallow is a React Hook for memoizing Zustand selector results with shallow comparison. It helps prevent unnecessary re-renders when computed objects or arrays are shallowly unchanged.
useStoreWithEqualityFnuseStoreWithEqualityFn connects a vanilla Zustand store to React while allowing a custom equality check. It is useful when a component needs selected store data and finer control over re-rendering.
createContextFunction

Hook

NameWhat it does
useStoreuseStore is a React Hook for reading and subscribing to a vanilla Zustand store. Pass it a store API and selector to obtain the selected current state.

Type Alias

NameWhat it does
StateCreatorStateCreator 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.
StoreApiType Alias
UseBoundStoreType Alias
StoreMutatorIdentifierStoreMutatorIdentifier is Zustand's type-level identifier for middleware mutators. It appears in mutator tuples that describe how middleware changes a store's type.
ExtractStateExtractState derives a Zustand store’s complete state-and-actions type for reuse. It avoids manually redefining the store type in tests, utilities, or component props.
MutateType Alias
PersistOptionsPersistOptions configures storage, filtering, rehydration, and versioning for Zustand's persist middleware. The required name identifies the persisted store; other fields customize how state is saved and restored.
StorageValueType Alias
StateStorageStateStorage is Zustand persist’s adapter type for custom persistence backends. Implement it when state should be stored somewhere other than the default localStorage-based setup.
PersistStorageType Alias
WithReactType Alias
WriteType Alias
StoreApi.getStateType Alias
StoreApi.setStateStoreApi.setState applies an external update to a Zustand store and notifies subscribers. By default, object updates are shallow-merged; pass true to replace the entire state.
StoreApi.subscribeStoreApi.subscribe registers a callback that runs when the Zustand store updates. It is useful for external state management and returns an unsubscribe function for cleanup.
StoreApi.getInitialStateType Alias

Const

NameWhat it does
slices patternThe slices pattern splits a large Zustand store into focused creator functions and combines them into one bounded store. This keeps state modular while allowing actions to coordinate across slices.
selectorA Zustand selector is a function that extracts the state or action a component needs. Passing it to the store hook limits the subscription to that selected data.
equality functionConst
transient updatesConst
vanilla storecreateStore creates a standalone Zustand store without React. Its returned API supports reading, updating, subscribing to, and inspecting the store's state.
React context storeUse a vanilla Zustand store with React context when a store must be initialized from component props or injected into a subtree. Create it once in a provider, pass it through context, and consume selected slices with useStore.
auto-generating selectorsZustand's auto-generating selectors pattern augments a store with a typed use object. It creates one selector per key in getState(), allowing direct access such as store.use.bears() and store.use.increment().
store factoryA store factory is a function that creates a fresh Zustand vanilla store, optionally initialized with caller-provided state. It is useful for per-request or otherwise isolated stores.
computed valuesCompute derived values with a Zustand selector. If the selector creates an unchanged object or array, useShallow can prevent rerenders by comparing the result shallowly.
middleware compositionZustand middleware is composed by nesting state-creator wrappers, such as persist inside devtools, and passing the result directly to create. This lets one store combine persistence, debugging, reducers, Immer updates, or other documented extensions.
actions in storeZustand 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.
nested stateZustand's set merges only the store's top level. To update nested state safely, copy the nested object and overwrite the changed property; deeper updates require copying each object level involved.
reset stateAdd a reset action that applies the store’s captured initial state. For multiple stores, collect reset callbacks and invoke them together.
derived stateConst
subscribe with selectorsubscribeWithSelector adds selector-based subscriptions to a Zustand state creator. Listeners can react to changes in a selected slice, such as one nested field, instead of subscribing to the whole state.
fireImmediatelyConst
replace flagThe replace flag is the second argument to Zustand’s set or setState functions. Set it to true to replace the entire store state instead of shallow-merging an update.
ref countingConst
SSR hydrationSSR renders a React app to HTML on the server, while hydration makes that markup interactive in the browser. The server and client must render matching output to avoid hydration errors.
Map and Set supportUse Map and Set values in Zustand by replacing them with newly created instances on every update. This preserves reference changes so Zustand can detect updates and re-render subscribers.
temporal (zundo)Const
mutative middlewareZustand's immer middleware enables immutable updates using mutable-style draft syntax. It wraps a state creator and lets Immer produce the next state from draft mutations.
Flux patternZustand recommends a Flux-inspired organization: keep global state in one store, update it through set or setState, and colocate actions with state. Large stores can use slices, while reducer-based Redux patterns remain optional.
single storeZustand recommends keeping an application's global state in a single store. Large stores can be organized with slices while remaining one bounded store.
multiple storesZustand supports multiple stores for separate domains, such as bears and fish. Each store remains isolated and can have its own strict TypeScript type.
store slicingZustand's slices pattern splits a large store into modular state-and-action creators, then combines them into one bounded store. Slice actions can coordinate through get(), while middleware belongs on the combined store.
middleware orderZustand middleware is nested, and devtools should usually be the outermost wrapper. With Immer, use devtools(immer(...)) so DevTools is applied last and other middleware cannot mutate setState first.
persist rehydrationPersist rehydration retrieves saved state from storage and merges it with the current Zustand state. It can happen automatically or be triggered manually through the persist API.
selector subscriptionsubscribeWithSelector adds selector-based subscriptions to a Zustand store. It lets subscribers react to selected partial state instead of requiring subscriptions to the entire state.
computed selectorsA computed selector derives a subscribed value from Zustand state instead of storing duplicate data. Zustand uses Object.is for the result by default; useShallow helps when recreated objects or arrays remain shallowly equal.
memoized selectorsuseShallow wraps a Zustand selector with shallow-result memoization. It helps React components avoid re-rendering when selected object or array contents have not changed.
React bindingscreate creates a React-bound Zustand hook from a state creator. Components use selectors with the hook to subscribe to the state they need, while store API utilities are attached to the hook.
context provider patternThe context provider pattern supplies a vanilla Zustand store through React context. A custom hook retrieves that store and uses selectors to subscribe components to the state they need.
testing storesThe testing guide shows how to mock Zustand's creators and reset every store to its initial state after each test. The pattern supports both React-bound and standalone stores.
resetting stateAdd a reset action that calls set(store.getInitialState()) to restore a Zustand store's initial state. For multiple stores, register reset callbacks and invoke them together.
async actionsZustand actions can be asynchronous: fetch remote data, await its typed response, and update store state with set. No special middleware is required for the documented pattern.
atomic selectorsAtomic selectors select only the state a component needs, including multiple fields grouped into one object. Use useShallow with object-returning selectors to avoid rerenders when selected values remain shallowly equal.
shallow equalityshallow compares two values using top-level equality rules. It is useful for fast checks of simple structures, but it does not recursively compare nested data.
ref-counted subscriptionsConst
store compositionThe slices pattern composes several focused Zustand state creators into one bounded store. It improves modularity while preserving a single store API.
immer producerThe immer middleware enables convenient immutable updates in Zustand. Wrap a state creator with it to write draft mutations inside set callbacks.
nested updatesZustand nested updates are immutable: copy each object along the path with spreads, then replace the target value. The set function shallowly merges the returned top-level object, so nested levels must be merged explicitly.
no provider neededZustand's React hook can be used directly in components without a provider. Selectors subscribe each component to the state it needs.
action creatorsZustand 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.
store typingZustand store typing uses a state-and-actions type with the curried create<T>()(...) form. This provides compile-time checking and typed selectors without requiring an interface when TypeScript can infer the shape.

Module

NameWhat it does
setZustand’s set function updates store state using a partial object or an updater function. It shallowly merges top-level fields by default, while a replacement flag can replace the entire state.
getModule
getStategetState is an imperative API attached to a Zustand hook created with create. It returns the store's current state, enabling reads and action calls outside React component rendering.
setStateZustand's setState updates a store from a partial value or updater function. It shallow-merges object updates by default, or replaces the entire state when replace is true.
subscribesubscribe registers a listener for updates to a Zustand vanilla store. It is useful for reacting to state changes in external, non-React code.
destroyModule
getInitialStategetInitialState is an imperative API attached to Zustand stores created with create. It returns the store's initial state, commonly used to implement reset actions.
setState (replace)Zustand’s setState replaces the entire store when called with true as its second argument. The replacement must be complete because omitted state properties—including actions—are discarded.
useStore.getStateModule
useStore.setStateuseStore.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.
useStore.subscribeuseStore.subscribe registers a callback that runs when the Zustand store updates. It returns an unsubscribe function for removing the listener.
store.getStateModule
store.setStatestore.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.
useStoreApiuseStore lets React components consume and subscribe to a vanilla Zustand store. Pass a StoreApi and optionally a selector to read either the full state or a derived slice.
getStoragegetStorage is the factory callback passed to createJSONStorage. It returns a Zustand-compatible storage engine so persist can save JSON-encoded state in browser storage or a custom backend.

Pipe

NameWhat it does
partializepartialize is a persist option that chooses which store fields are written to storage. Return a smaller object to keep selected state across reloads while excluding transient fields.
onRehydrateStorageonRehydrateStorage lets a persisted Zustand store run logic when storage hydration starts and optionally when it finishes. The completion callback receives the hydrated state and any hydration error.
storageThe persist middleware saves Zustand state across page reloads or application restarts. Configure a unique storage key and optionally provide a custom storage adapter.
versionThe persist middleware's version option labels the persisted state format. Change it for breaking storage changes, and use migration logic to convert older data to the current shape.
migratemigrate transforms persisted Zustand state when its stored version differs from the configured version. It receives the old state and version, then returns state compatible with the latest schema, synchronously or asynchronously.
mergePipe
skipHydrationskipHydration is a Zustand persist option that prevents automatic hydration when a store is initialized. Enable it when the application needs to call rehydrate() at a controlled time, such as during SSR.
nameThe persist middleware's required name option is the storage key for a Zustand store's persisted state. It must be unique.
anonymousActionTypeanonymousActionType is an optional devtools setting that names mutations lacking an explicit action type in Redux DevTools. It overrides the anonymous fallback when no inferred type is available.
tracePipe
enabledPipe
storeZustand's create builds a hook-based store containing state and actions. Components select the data they need, and set applies merged updates without requiring a provider.
serializePipe
deserializePipe
equalityFncreateWithEqualityFn creates a React hook like create but adds configurable equality checking for selector results. Use it to avoid re-renders when a selected value is considered equal by the comparator.
getStorage optiongetStorage is the lazy callback used by createJSONStorage to obtain a custom storage engine. The engine must provide getItem, setItem, and removeItem; the helper returns a persistence-ready storage object.
limit (devtools)Pipe

Search across every package and filter by type in your dashboard.

Start learning