Read derived state
A component needs a list, count, or other value derived from several store fields.
Zustand · Const
Compute derived values with a Zustand selector. If the selector creates an unchanged object or array, useShallow can prevent rerenders by comparing the result shallowly.
A computed value is obtained by passing a selector to the store hook. Zustand compares the selector result with Object.is; when the selector creates a new object or array whose contents are effectively unchanged, useShallow can compare its entries and prevent unnecessary rerenders.
useStore(selector)
useStore(useShallow(selector))The selected computed value for use in the component.
import { create } from 'zustand'
import { useShallow } from 'zustand/react/shallow'
type Meals = {
papaBear: string
mamaBear: string
littleBear: string
}
const useMeals = create<Meals>(() => ({
papaBear: 'large porridge-pot',
mamaBear: 'middle-size porridge pot',
littleBear: 'A little, small, wee pot',
}))
export function BearNames() {
const names = useMeals(useShallow((state) => Object.keys(state)))
return <div>{names.join(', ')}</div>
}The component derives an array of property names and uses shallow comparison so unchanged array contents do not trigger an unnecessary rerender.
A component needs a list, count, or other value derived from several store fields.
A selector allocates an object or array on every evaluation but its shallow contents usually stay the same.
A component should react only to a computed projection of store data rather than unrelated fields.
A computed value is normally produced with a selector, such as (state) => Object.keys(state). The component subscribes to that selector's result rather than the entire store.
Follow-up: What determines whether the component rerenders? The selector output is checked with Object.is, so a changed reference can be significant.
Object.is compares the selector result with its previous result. A newly allocated array or object therefore counts as changed even when it contains the same shallow values.
Follow-up: How can this be improved for shallowly equal results? Wrap the selector with useShallow so Zustand compares the selected entries shallowly.
useShallow is useful when a selector repeatedly returns a result that is shallowly equal to the previous result. It lets the component avoid rerendering for unrelated store updates that do not alter those shallow values.
Follow-up: When should it not be used? It is not a deep comparison; nested changes require a comparison strategy appropriate to the selected data.
useShallowshallowselectors