Share state through a vanilla store API
Framework-independent state
Zustand · Function
createStore creates a vanilla Zustand store with an imperative API. Pass a state creator to define its state and actions.
Call the curried function with a state creator to build a vanilla store. The creator defines initial state and actions; the returned store exposes methods for reading, updating, subscribing, and retrieving initial state.
createStore<T>()(stateCreatorFn: StateCreator<T, [], []>): StoreApi<T>| Name | Type | Description |
|---|---|---|
stateCreatorFn | StateCreator<T, [], []> | A function receiving set, get, and store; it generally returns the state and methods exposed by the store. |
A vanilla store API of type StoreApi<T>, exposing setState, getState, getInitialState, and subscribe.
import { createStore } from 'zustand/vanilla'
type CounterStore = {
count: number
increment: () => void
}
const counterStore = createStore<CounterStore>()((set) => ({
count: 0,
increment: () => set((state) => ({ count: state.count + 1 })),
}))
counterStore.getState().increment()
console.log(counterStore.getState().count)
Creates a vanilla counter store, updates it through an action, and reads the resulting state.
Framework-independent state
Imperative application code
External observers
createStore builds a vanilla Zustand store rather than a React-bound hook. Its result provides state-management utilities including setState, getState, getInitialState, and subscribe.
Follow-up: How would you connect it to React? Use Zustand's store-consuming integration and select the state needed by a component, while keeping the vanilla store as the underlying API.
The state creator receives set, get, and store. It normally returns the state fields and methods that the store should expose.
Follow-up: Why avoid calling those arguments during initialization? The documentation says they are only safe after creation, so defer such calls to action execution or later lifecycle code.
The documented signature is createStore<T>()(stateCreatorFn: StateCreator<T, [], []>): StoreApi<T>. The first call supplies the state type, and the second accepts the state creator.
Follow-up: When is a vanilla store useful? It is appropriate when store access should be exposed through an API object independently of a React hook.
createStoreApisetStategetStategetInitialStatesubscribeStateCreator