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
| Name | What it does |
|---|---|
create | |
createStore | createStore creates a vanilla Zustand store with an imperative API. Pass a state creator to define its state and actions. |
persist | The persist middleware saves Zustand store state across page reloads or application restarts. It supports custom storage, selective persistence, version migration, merging, and controlled rehydration. |
immer | The immer middleware lets Zustand updates use mutable-looking draft syntax while producing immutable state. Wrap a state creator with it to simplify nested updates. |
subscribeWithSelector | subscribeWithSelector adds selector-based subscriptions to a Zustand store. Listeners can react to changes in selected data instead of observing unrelated state updates. |
combine | Zustand'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. |
devtools | The 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. |
shallow | shallow 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. |
createWithEqualityFn | createWithEqualityFn creates a React hook store like create, while allowing a default equality function. Equality checks give finer control over selector-driven re-renders. |
redux | Zustand's redux middleware builds a store from a reducer and initial state. It adds typed action dispatching while retaining Zustand's store APIs. |
createJSONStorage | Creates a Zustand persistence storage adapter around a custom storage engine. It serializes and parses persisted values as JSON, with optional replacer and reviver customization. |
useShallow | useShallow 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. |
useStoreWithEqualityFn | useStoreWithEqualityFn 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. |
createContext |
Hook
| Name | What it does |
|---|---|
useStore | useStore 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
| Name | What it does |
|---|---|
StateCreator | 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. |
StoreApi | |
UseBoundStore | |
StoreMutatorIdentifier | StoreMutatorIdentifier is Zustand's type-level identifier for middleware mutators. It appears in mutator tuples that describe how middleware changes a store's type. |
ExtractState | ExtractState 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. |
Mutate | |
PersistOptions | PersistOptions 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. |
StorageValue | |
StateStorage | StateStorage 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. |
PersistStorage | |
WithReact | |
Write | |
StoreApi.getState | |
StoreApi.setState | StoreApi.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.subscribe | StoreApi.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.getInitialState |
Const
| Name | What it does |
|---|---|
slices pattern | The 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. |
selector | A 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 function | |
transient updates | |
vanilla store | createStore creates a standalone Zustand store without React. Its returned API supports reading, updating, subscribing to, and inspecting the store's state. |
React context store | Use 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 selectors | Zustand'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 factory | A 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 values | Compute 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 composition | Zustand 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 store | 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. |
nested state | Zustand'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 state | Add a reset action that applies the store’s captured initial state. For multiple stores, collect reset callbacks and invoke them together. |
derived state | |
subscribe with selector | subscribeWithSelector 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. |
fireImmediately | |
replace flag | The 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 counting | |
SSR hydration | SSR 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 support | Use 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) | |
mutative middleware | Zustand'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 pattern | Zustand 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 store | Zustand recommends keeping an application's global state in a single store. Large stores can be organized with slices while remaining one bounded store. |
multiple stores | Zustand supports multiple stores for separate domains, such as bears and fish. Each store remains isolated and can have its own strict TypeScript type. |
store slicing | Zustand'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 order | Zustand 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 rehydration | Persist 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 subscription | subscribeWithSelector 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 selectors | A 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 selectors | useShallow 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 bindings | create 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 pattern | The 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 stores | The 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 state | Add 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 actions | Zustand 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 selectors | Atomic 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 equality | shallow 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 subscriptions | |
store composition | The slices pattern composes several focused Zustand state creators into one bounded store. It improves modularity while preserving a single store API. |
immer producer | The immer middleware enables convenient immutable updates in Zustand. Wrap a state creator with it to write draft mutations inside set callbacks. |
nested updates | Zustand 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 needed | Zustand's React hook can be used directly in components without a provider. Selectors subscribe each component to the state it needs. |
action creators | 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. |
store typing | Zustand 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
| Name | What it does |
|---|---|
set | Zustand’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. |
get | |
getState | getState 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. |
setState | Zustand'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. |
subscribe | subscribe registers a listener for updates to a Zustand vanilla store. It is useful for reacting to state changes in external, non-React code. |
destroy | |
getInitialState | getInitialState 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.getState | |
useStore.setState | 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. |
useStore.subscribe | useStore.subscribe registers a callback that runs when the Zustand store updates. It returns an unsubscribe function for removing the listener. |
store.getState | |
store.setState | store.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. |
useStoreApi | useStore 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. |
getStorage | getStorage 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
| Name | What it does |
|---|---|
partialize | partialize 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. |
onRehydrateStorage | onRehydrateStorage 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. |
storage | The persist middleware saves Zustand state across page reloads or application restarts. Configure a unique storage key and optionally provide a custom storage adapter. |
version | The 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. |
migrate | migrate 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. |
merge | |
skipHydration | skipHydration 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. |
name | The persist middleware's required name option is the storage key for a Zustand store's persisted state. It must be unique. |
anonymousActionType | anonymousActionType 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. |
trace | |
enabled | |
store | Zustand'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. |
serialize | |
deserialize | |
equalityFn | createWithEqualityFn 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 option | getStorage 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) |
Search across every package and filter by type in your dashboard.
Start learning