Derive values without duplicated state
A component needs a count, total, label, or other value calculated from existing fields.
Zustand · Const
A computed selector derives a subscribed value from Zustand state instead of storing duplicate data. Zustand uses Object.is for the result by default; useShallow helps when recreated objects or arrays remain shallowly equal.
A computed selector derives a value from the current Zustand state instead of storing a duplicate value. Zustand compares the selector result with Object.is by default; useShallow can prevent rerenders when a newly created result is shallowly equal to the previous result.
useStore((state) => derivedValue)| Name | Type | Description |
|---|---|---|
state | Store state | The current Zustand state supplied to the selector. |
selector | (state) => selectedValue | A function that derives the subscribed value from state. |
The value produced by the selector from the current store state.
import { create } from 'zustand'
import { useShallow } from 'zustand/react/shallow'
type MealState = {
meals: Record<string, string>
}
const useMeals = create<MealState>(() => ({
meals: {
papaBear: 'large porridge-pot',
mamaBear: 'middle-size porridge pot',
littleBear: 'small pot',
},
}))
export function MealNames() {
const names = useMeals(useShallow((state) => Object.keys(state.meals)))
return <div>{names.join(', ')}</div>
}The selector computes an array of meal names, while useShallow avoids rerendering when that array remains shallowly equal.
A component needs a count, total, label, or other value calculated from existing fields.
A selector returns Object.keys, a mapped array, or a composite object on every evaluation.
A component should react only to a derived slice rather than every store update.
A selector receives the current store state and returns the value a component should subscribe to. For derived data, it computes that value on demand rather than adding duplicated state.
Follow-up: What happens when the selector returns a new array each time? Zustand may rerender because Object.is sees a different reference; useShallow can avoid this when the contents are shallowly equal.
Zustand compares a selector's output with Object.is by default. Therefore, a new object or array reference is considered changed even if its entries have not changed.
Follow-up: How can you optimize a selector returning Object.keys(state)? Wrap the selector with useShallow so shallowly equal arrays do not cause unnecessary rerenders.
useShallow wraps a selector and compares its result shallowly. This is useful when the selector creates a new object or array whose top-level values remain equal.
Follow-up: When should useShallow not be the first choice? Prefer selecting a primitive or stable state field directly when that expresses the requirement without constructing a composite result.
useShallowcreateuseStoresubscribeWithSelectorselectors