Cross-environment state
State shared by React and non-React code
Zustand · Const
createStore creates a standalone Zustand store without React. Its returned API supports reading, updating, subscribing to, and inspecting the store's state.
Call createStore with a state creator to produce a standalone Zustand store. The resulting API exposes state access, updates, initialization data, and subscriptions, so the store can be used without React and connected to consumers separately.
createStore<T>()(stateCreatorFn: StateCreator<T, [], []>): StoreApi<T>| Name | Type | Description |
|---|---|---|
stateCreatorFn | StateCreator<T, [], []> | A function receiving set, get, and store, and returning the store's initial state and actions. |
A vanilla store exposing API utilities, setState, getState, getInitialState, and subscribe.
createStore when state must exist independently of React, such as in a framework-agnostic module or shared application service.StoreApi.set for updates, get for reading current state, and store for the store API.set, get, or store arguments while the store is being initialized; use them after creation, such as inside actions.import { createStore } from 'zustand/vanilla'
type CounterState = {
count: number
increment: () => void
}
const counterStore = createStore<CounterState>()((set) => ({
count: 0,
increment: () => set((state) => ({ count: state.count + 1 })),
}))
const unsubscribe = counterStore.subscribe((state) => {
console.log(state.count)
})
counterStore.getState().increment()
unsubscribe()This creates a standalone store, updates its state through an action, observes changes, and removes the listener.
State shared by React and non-React code
Imperative state access in services, event handlers, or integrations
A store instance passed into a React context or hook
createStore return?createStore builds a vanilla store from a state creator and returns a StoreApi<T>. Unlike the React-bound creator, it does not provide a React hook; consumers use the returned API directly.
Follow-up: How would React consume it? Pass the vanilla store to Zustand's useStore hook and select the needed state.
The state creator receives set, get, and store. It returns the initial state together with actions, while updates should be performed through set.
Follow-up: Why put updates in actions? Actions colocate mutation logic with the state and let callers trigger updates without directly constructing state changes.
The returned store exposes setState, getState, getInitialState, and subscribe. subscribe lets external consumers react to state changes without requiring React.
Follow-up: When is a vanilla store especially useful? It is suitable for non-React environments and for sharing one store API across React and vanilla consumers.
createuseStoreuseStoreWithEqualityFnpersistStoreApi