Consume a vanilla store
A store must be created outside React and consumed by components.
Zustand · Hook
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.
useStore connects a vanilla Zustand store to a React component. It receives the store API and a selector, subscribes the component to store updates, and returns the selector's current result.
useStore<T, U>(storeApi: StoreApi<T>, selectorFn: (state: T) => U): U| Name | Type | Description |
|---|---|---|
storeApi | StoreApi<T> | The vanilla store instance used by the hook and exposing the store API. |
selectorFn | (state: T) => U | A function that receives current state and returns the value to read. |
The value returned by selectorFn for the store's current state.
import { createStore, useStore } from 'zustand'
import { useRef } from 'react'
type CounterState = {
count: number
increment: () => void
}
function Counter() {
const storeRef = useRef<ReturnType<typeof createCounterStore> | null>(null)
if (storeRef.current === null) storeRef.current = createCounterStore()
const count = useStore(storeRef.current, (state) => state.count)
const increment = useStore(storeRef.current, (state) => state.increment)
return <button onClick={increment}>{count}</button>
}
function createCounterStore() {
return createStore<CounterState>((set) => ({
count: 0,
increment: () => set((state) => ({ count: state.count + 1 })),
}))
}A vanilla store is created once, then useStore subscribes the component to separate selected values.
A store must be created outside React and consumed by components.
A provider supplies different store instances to different component subtrees.
A component needs only one field or action from a larger store.
useStore is a React Hook for using a vanilla store in React. Its arguments are the store instance and a selector function, and it returns the selector's value from current state.
Follow-up: How would you expose a context-backed store safely? Read the store with useContext, throw when it is absent, then call useStore(store, selector).
The selector receives the store state and chooses the data the component needs. The hook subscribes the component to the store so that selected data stays current.
Follow-up: How can a component read multiple independent values? Call useStore separately with selectors for each value, or select a combined value when appropriate.
useStore is intended for vanilla stores, whose API object is passed directly to the hook. This makes it suitable when a store is created separately from a React-bound hook.
Follow-up: Why use a context wrapper? It lets the application provide a store instance and centralize the missing-provider check before delegating to useStore.
createcreateStoreuseStoreWithEqualityFnuseShallow