Consume a vanilla store
A store is created with createStore from the vanilla package and must be read in a React component.
Zustand · Module
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.
useStore connects a vanilla Zustand store to a React component. It receives the store API and an optional selector, subscribes the component to the selected result, and returns that current value for rendering.
useStore<T, U = T>(store: StoreApi<T>, selectorFn?: (state: T) => U): U| Name | Type | Description |
|---|---|---|
storeApi | StoreApi<T> | The StoreApi instance used to access the vanilla store and its utilities. |
selectorFn | (state: T) => U | Optional function that derives the value returned from the current state. |
The selected data derived from the store's current state; without a selector, the complete state value.
import { createStore } from 'zustand/vanilla'
import { useStore } from 'zustand'
import { createRoot } from 'react-dom/client'
const counterStore = createStore(() => ({ count: 0 }))
function Counter() {
const count = useStore(counterStore, (state) => state.count)
return <button onClick={() => counterStore.setState({ count: count + 1 })}>{count}</button>
}
createRoot(document.getElementById('root')!).render(<Counter />)Pass a vanilla store and selector to useStore to subscribe a React component to one state slice.
A store is created with createStore from the vanilla package and must be read in a React component.
A component needs only one field or computed value from a larger store.
A store API is supplied through a provider or another dependency boundary.
useStore is a React Hook for consuming a vanilla Zustand store. It accepts a StoreApi and optionally a selector, then returns the selected data from the current state.
Follow-up: How would you limit re-renders? Select the smallest useful slice rather than returning the entire state object.
The first parameter is the store API, and the optional selector receives the store state and returns the value needed by the component. Without a selector, the hook can return the complete current state.
Follow-up: How can a component consume a store held in context? Read the StoreApi from context, then pass it to useStore with the component's selector.
The hook returns data based on the current state, according to the selector function. Its type is useStore<T, U = T>(store: StoreApi<T>, selectorFn?: (state: T) => U): U.
Follow-up: What type should a selector have when selecting a derived value? It should accept the full state type and return the derived slice type.
StoreApicreateStoreuseStoreWithEqualityFncreate