Read a single value
A component displays one field such as a count and should not depend on unrelated store updates.
Zustand · Const
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.
A selector is a function passed to a Zustand store hook that extracts the portion of state a component needs. The component then subscribes to that selected result rather than reading the entire store, while actions can be selected in the same way.
useStore(selectorFn)
useStore(storeApi, selectorFn)| Name | Type | Description |
|---|---|---|
storeApi | StoreApi<T> | The store instance used for selecting state, when using useStore with a vanilla store. |
selectorFn | (state: T) => U | A function that returns data derived from the current state. |
The selected data derived from the current state; with useStore, the return type is U.
import { create } from 'zustand'
type BearStore = {
bears: number
increment: () => void
}
const useBearStore = create<BearStore>((set) => ({
bears: 0,
increment: () => set((state) => ({ bears: state.bears + 1 })),
}))
export function BearCount() {
const bears = useBearStore((state) => state.bears)
return <button onClick={useBearStore.getState().increment}>{bears}</button>
}The component subscribes only to the bears value by passing a selector to the store hook.
A component displays one field such as a count and should not depend on unrelated store updates.
A component needs several state fields together.
A component derives a computed list or value from store state.
A selector is a function such as state => state.bears that returns the data a component needs. The store hook uses that result for the component's subscription.
Follow-up: What happens when the selector returns an object? A new object may fail Object.is comparison and rerender the component; useShallow when shallow equality is appropriate.
A selector can return more than one property by returning an object. Without additional equality handling, destructuring that object can cause unnecessary rerenders.
Follow-up: How can this be improved? Wrap the selector with useShallow so unchanged shallow values do not cause a rerender.
useStore accepts a vanilla store and an optional selector. The selector returns data derived from the current state, and useStore returns that selected data.
Follow-up: Why use a selector with a vanilla store? It lets React subscribe to the relevant slice instead of treating the whole state as the component's required value.
useShallowuseStoresubscribeWithSelectorcreate