# Select computed state

Use a selector when a component needs several store values or a computed collection. Wrap object and array selections in [`useShallow`](https://bench-zustand-61.atloria.app/p/bench-zustand-61-pSJCWrWW5Y/developer/zustand-shallow#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](https://bench-zustand-61.atloria.app/p/bench-zustand-61-pSJCWrWW5Y/developer/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`](https://bench-zustand-61.atloria.app/p/bench-zustand-61-pSJCWrWW5Y/developer/zustand#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 title="src/meals-store.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`](https://bench-zustand-61.atloria.app/p/bench-zustand-61-pSJCWrWW5Y/developer/zustand#usestore) reads the guest's presence from the same store API and disables the button after the guest is added.

```tsx title="src/FamilyMeals.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.](https://atloriaassets.blob.core.windows.net/assets/a438221c-c1af-407c-b9e6-a56c986db846/59d7ee46c28d58318816d4120bc2e7b2.png)

## 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 title="src/MealPicks.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.](https://atloriaassets.blob.core.windows.net/assets/a438221c-c1af-407c-b9e6-a56c986db846/71e8c23bb7ebea3ec490fa8063c4dc97.png)

### Mount and try the example

In the [React quick start's entry file](https://bench-zustand-61.atloria.app/p/bench-zustand-61-pSJCWrWW5Y/developer/react-quick-start), 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`](https://bench-zustand-61.atloria.app/p/bench-zustand-61-pSJCWrWW5Y/developer/zustand-react-shallow#useshallow) from `zustand/react/shallow`.

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

| Selection | Result | Equality behavior |
| --- | --- | --- |
| Separate selectors, such as `(state) => state.papaBear` | Each selected value | Default `Object.is` comparison; no wrapper needed. |
| Object wrapped in `useShallow` | Named values | Compares top-level property values with `Object.is`. |
| Array or tuple wrapped in `useShallow` | Ordered values | Compares values at matching indices; changing length or order can change the result. |
| `Object.keys(state)` wrapped in `useShallow` | Computed names | Retains 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](https://bench-zustand-61.atloria.app/p/bench-zustand-61-pSJCWrWW5Y/developer/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](https://bench-zustand-61.atloria.app/p/bench-zustand-61-pSJCWrWW5Y/developer/customize-equality-and-subscriptions).

## Demo and related guides

Explore the [live Zustand demo](https://zustand-demo.pmnd.rs/) for a mounted store-hook example. The meal example above applies computed and multi-value selections to that hook-based pattern.

- [Selectors and rendering](https://bench-zustand-61.atloria.app/p/bench-zustand-61-pSJCWrWW5Y/developer/selectors-and-rendering) explains subscription boundaries and output identity.
- [Type stores and selectors](https://bench-zustand-61.atloria.app/p/bench-zustand-61-pSJCWrWW5Y/developer/type-stores-and-selectors) covers typing selectors and store APIs.
