Skip to content
D
Documentation

Select computed state

how-to
3 min readUpdated

Use a selector when a component needs several store values or a computed collection. Wrap object and array selections in useShallow to keep their output reference while their top-level contents remain equal.

The example displays bear names and their meals. Changing a meal updates the meal display without triggering a store-driven render of the names component; adding a bear updates the names too.

Start from the project in the React quick start. It already has React, TypeScript, and Zustand installed. The imports below come from that same zustand package; no additional installation is needed.

Writing a memoized selector

1. Define the meals store

Add src/meals-store.ts. create binds this independent store to the useMeals hook. Keep only meal data in this store so Object.keys(state) returns bear names rather than action names.

ts
import { create } from 'zustand'

type MealsState = {
  papaBear: string
  mamaBear: string
  babyBear: string
  guestBear?: string
}

export const useMeals = create<MealsState>()(() => ({
  papaBear: 'large porridge-pot',
  mamaBear: 'middle-size porridge pot',
  babyBear: 'A little, small, wee pot',
}))

2. Select names and update meals

Add src/FamilyMeals.tsx. Call useShallow inside the component and pass its returned selector to the store hook. BearNames receives a string[]; the wrapper returns the previous array when the new array contains the same names in the same order.

The timer changes baby's meal every second. The pizza button changes papa's meal, following the same partial-update pattern. Neither update changes the keys. The guest button adds a key once, so the names selection changes. useStore reads the guest's presence from the same store API and disables the button after the guest is added.

tsx
import { useEffect } from 'react'
import { useStore } from 'zustand'
import { useShallow } from 'zustand/shallow'
import { useMeals } from './meals-store'
import MealPicks from './MealPicks'

function BearNames() {
  const names = useMeals(useShallow((state) => Object.keys(state)))

  return <p>Names: {names.join(', ')}</p>
}

function UpdateBabyBearMeal() {
  useEffect(() => {
    const timer = setInterval(() => {
      useMeals.setState((state) => ({
        babyBear:
          state.babyBear === 'A tiny, little, wee bowl'
            ? 'A small, petite, tiny pot'
            : 'A tiny, little, wee bowl',
      }))
    }, 1000)

    return () => clearInterval(timer)
  }, [])

  return null
}

export default function FamilyMeals() {
  const hasGuest = useStore(useMeals, (state) => state.guestBear !== undefined)

  return (
    <main style={{ minHeight: 400, padding: 24 }}>
      <h1>Bear family meals</h1>
      <UpdateBabyBearMeal />
      <BearNames />
      <MealPicks />
      <button
        type="button"
        onClick={() => useMeals.setState({ papaBear: 'a large pizza' })}
      >
        Order pizza for papa
      </button>
      <button
        type="button"
        disabled={hasGuest}
        onClick={() => useMeals.setState({ guestBear: 'a bowl of porridge' })}
      >
        Add guest bear
      </button>
    </main>
  )
}

setState shallowly merges each partial update, preserving the other meals. The effect clears its interval when the component unmounts.

Bear family names, parent meals, baby's meal, and the pizza and guest buttons.

Select multiple values

Add src/MealPicks.tsx, imported by the preceding component. An object selection gives named fields; a tuple selection gives positional values. Both use useShallow so allocating the wrapper does not itself count as a change.

tsx
import { useShallow } from 'zustand/shallow'
import { useMeals } from './meals-store'

function ParentMeals() {
  const { papaMeal, mamaMeal } = useMeals(
    useShallow((state) => ({
      papaMeal: state.papaBear,
      mamaMeal: state.mamaBear,
    })),
  )

  return (
    <section>
      <h2>Parent meals</h2>
      <p>Papa: {papaMeal}</p>
      <p>Mama: {mamaMeal}</p>
    </section>
  )
}

function BabyMeal() {
  const [name, meal] = useMeals(
    useShallow((state): [string, string] => ['babyBear', state.babyBear]),
  )

  return <p>{name}: {meal}</p>
}

export default function MealPicks() {
  return (
    <>
      <ParentMeals />
      <BabyMeal />
    </>
  )
}

Baby's timer updates BabyMeal, not ParentMeals: the selected parent strings remain equal. Ordering pizza updates ParentMeals. Adding a guest updates BearNames without changing either meal selection.

The meal selections display papa's, mama's, and baby's initial meals.

Mount and try the example

In the React quick start's entry file, import FamilyMeals from ./FamilyMeals.tsx and render <FamilyMeals /> in place of the counter.

bash
npm run build
npm run dev

Open the local URL printed by Vite. You see the three initial names, papa's and mama's meals, baby's changing meal, and two buttons. Click Order pizza for papa to display a large pizza. Click Add guest bear once to append guestBear to the names; the button then becomes disabled.

Choose the selector output

useShallow takes a selector (state: S) => U and returns a selector with the same input and output types. It memoizes the output, not the computation: it still calls your selector, then compares the result with its previous result. The hook is also exported as useShallow from zustand/react/shallow.

There is no options object or comparison setting to pass to useShallow. Choose the shape your component needs:

SelectionResultEquality behavior
Separate selectors, such as (state) => state.papaBearEach selected valueDefault Object.is comparison; no wrapper needed.
Object wrapped in useShallowNamed valuesCompares top-level property values with Object.is.
Array or tuple wrapped in useShallowOrdered valuesCompares values at matching indices; changing length or order can change the result.
Object.keys(state) wrapped in useShallowComputed namesRetains the array while its strings remain equal in the same order.

Keep outputs stable

In Zustand v5, selectors that repeatedly return a new object, array, or fallback function can cause infinite update loops, including a “Maximum update depth exceeded” error. This applies to hooks bound by create and to useStore. Wrap shallow-equal objects and arrays in useShallow, or subscribe to each value separately. If a selector supplies a fallback function, define that function outside the component and return the stable reference instead of creating it inside the selector.

Shallow comparison does not compare nested contents. If a selector builds a new object for every array element, those element references differ on every evaluation. Select existing object references or primitive values instead. For state changes themselves, follow Immutable state and merging.

useShallow prevents a store-driven render when the selected output remains equal. It does not prevent renders caused by a parent or the component's own React state. For a different equality policy, see Customize equality checks.

Explore the live Zustand demo for a mounted store-hook example. The meal example above applies computed and multi-value selections to that hook-based pattern.

Was this page helpful?