use-shallow.md
This file
Path
docs/reference/hooks/use-shallow.md
300 lines · 7.1 KiB · Markdown
Last changed by
docs(use-shallow): add troubleshooting entry for "Maximum update depth exceeded" (#3507)seunghyunbefore adoption4e15c2e
History of this fileTake it
Revamping docs - file restructuring (#3392)Danilo Brittobefore adoption8eae4e9
lines 1–20why, one step back1---2title: useShallow3description: How to memoize selector functions4tag: react5nav: 276---78`useShallow` is a React Hook that lets you optimize re-renders.910```js11const memoizedSelector = useShallow(selector)12```1314- [Types](#types)15 - [Signature](#signature)16- [Reference](#reference)17- [Usage](#usage)18 - [Writing a memoized selector](#writing-a-memoized-selector)19- [Troubleshooting](#troubleshooting)20Hotfix section linking (#3410)Copilotbefore adoptionc49df38
lines 21–22why, one step back21## Types22Revamping docs - file restructuring (#3392)Danilo Brittobefore adoption8eae4e9
lines 23–268why, one step back23### Signature2425```ts26useShallow<T, U = T>(selectorFn: (state: T) => U): (state: T) => U27```2829## Reference3031### `useShallow(selectorFn)`3233#### Parameters3435- `selectorFn`: A function that lets you return data that is based on current state.3637#### Returns3839`useShallow` returns a memoized version of a selector function using a shallow comparison for40memoization.4142## Usage4344### Writing a memoized selector4546First, we need to setup a store to hold the state for the bear family. In this store, we define47three properties: `papaBear`, `mamaBear`, and `babyBear`, each representing a different member of48the bear family and their respective oatmeal pot sizes.4950```tsx51import { create } from 'zustand'5253type BearFamilyMealsStore = {54 [key: string]: string55}5657const useBearFamilyMealsStore = create<BearFamilyMealsStore>()(() => ({58 papaBear: 'large porridge-pot',59 mamaBear: 'middle-size porridge pot',60 babyBear: 'A little, small, wee pot',61}))62```6364Next, we'll create a `BearNames` component that retrieves the keys of our state (the bear family65members) and displays them.6667```tsx68function BearNames() {69 const names = useBearFamilyMealsStore((state) => Object.keys(state))7071 return <div>{names.join(', ')}</div>72}73```7475Next, we will create a `UpdateBabyBearMeal` component that periodically updates baby bear's meal76choice.7778```tsx79const meals = [80 'A tiny, little, wee bowl',81 'A small, petite, tiny pot',82 'A wee, itty-bitty, small bowl',83 'A little, petite, tiny dish',84 'A tiny, small, wee vessel',85 'A small, little, wee cauldron',86 'A little, tiny, small cup',87 'A wee, small, little jar',88 'A tiny, wee, small pan',89 'A small, wee, little crock',90]9192function UpdateBabyBearMeal() {93 useEffect(() => {94 const timer = setInterval(() => {95 useBearFamilyMealsStore.setState({96 babyBear: meals[Math.floor(Math.random() * (meals.length - 1))],97 })98 }, 1000)99100 return () => {101 clearInterval(timer)102 }103 }, [])104105 return null106}107```108109Finally, we combine both components in the `App` component to see them in action.110111```tsx112export default function App() {113 return (114 <>115 <UpdateBabyBearMeal />116 <BearNames />117 </>118 )119}120```121122Here is what the code should look like:123124```tsx125import { useEffect } from 'react'126import { create } from 'zustand'127128type BearFamilyMealsStore = {129 [key: string]: string130}131132const useBearFamilyMealsStore = create<BearFamilyMealsStore>()(() => ({133 papaBear: 'large porridge-pot',134 mamaBear: 'middle-size porridge pot',135 babyBear: 'A little, small, wee pot',136}))137138const meals = [139 'A tiny, little, wee bowl',140 'A small, petite, tiny pot',141 'A wee, itty-bitty, small bowl',142 'A little, petite, tiny dish',143 'A tiny, small, wee vessel',144 'A small, little, wee cauldron',145 'A little, tiny, small cup',146 'A wee, small, little jar',147 'A tiny, wee, small pan',148 'A small, wee, little crock',149]150151function UpdateBabyBearMeal() {152 useEffect(() => {153 const timer = setInterval(() => {154 useBearFamilyMealsStore.setState({155 babyBear: meals[Math.floor(Math.random() * (meals.length - 1))],156 })157 }, 1000)158159 return () => {160 clearInterval(timer)161 }162 }, [])163164 return null165}166167function BearNames() {168 const names = useBearFamilyMealsStore((state) => Object.keys(state))169170 return <div>{names.join(', ')}</div>171}172173export default function App() {174 return (175 <>176 <UpdateBabyBearMeal />177 <BearNames />178 </>179 )180}181```182183Everything might look fine, but there’s a small problem: the `BearNames` component keeps184re-rendering even if the names haven’t changed. This happens because the component re-renders185whenever any part of the state changes, even if the specific part we care about (the list of names) hasn’t changed.186187To fix this, we use `useShallow` to make sure the component only re-renders when the actual keys of188the state change:189190```tsx191function BearNames() {192 const names = useBearFamilyMealsStore(193 useShallow((state) => Object.keys(state)),194 )195196 return <div>{names.join(', ')}</div>197}198```199200Here is what the code should look like:201202```tsx203import { useEffect } from 'react'204import { create } from 'zustand'205import { useShallow } from 'zustand/react/shallow'206207type BearFamilyMealsStore = {208 [key: string]: string209}210211const useBearFamilyMealsStore = create<BearFamilyMealsStore>()(() => ({212 papaBear: 'large porridge-pot',213 mamaBear: 'middle-size porridge pot',214 babyBear: 'A little, small, wee pot',215}))216217const meals = [218 'A tiny, little, wee bowl',219 'A small, petite, tiny pot',220 'A wee, itty-bitty, small bowl',221 'A little, petite, tiny dish',222 'A tiny, small, wee vessel',223 'A small, little, wee cauldron',224 'A little, tiny, small cup',225 'A wee, small, little jar',226 'A tiny, wee, small pan',227 'A small, wee, little crock',228]229230function UpdateBabyBearMeal() {231 useEffect(() => {232 const timer = setInterval(() => {233 useBearFamilyMealsStore.setState({234 babyBear: meals[Math.floor(Math.random() * (meals.length - 1))],235 })236 }, 1000)237238 return () => {239 clearInterval(timer)240 }241 }, [])242243 return null244}245246function BearNames() {247 const names = useBearFamilyMealsStore(248 useShallow((state) => Object.keys(state)),249 )250251 return <div>{names.join(', ')}</div>252}253254export default function App() {255 return (256 <>257 <UpdateBabyBearMeal />258 <BearNames />259 </>260 )261}262```263264By using `useShallow`, we optimized the rendering process, ensuring that the component only265re-renders when necessary, which improves overall performance.266267## Troubleshooting268docs(use-shallow): add troubleshooting entry for "Maximum update depth exceeded" (#3507)seunghyunbefore adoption4e15c2e
lines 269–300why, one step back269### I get "Maximum update depth exceeded" when reading multiple values from the store270271Since v5, selectors that return a new reference on every render can trigger infinite update loops because the default equality check is `Object.is`. The most common case is bundling multiple values into a single object inside the selector. The following triggers the error:272273```tsx274const { searchValue, setSearchValue } = useStore((state) => ({275 searchValue: state.searchValue,276 setSearchValue: state.setSearchValue,277}))278```279280The wrapper object is recreated on every render, so each comparison fails and the component re-subscribes in a loop.281282Wrap the selector with `useShallow` so the wrapper's properties are compared by reference instead of the wrapper itself:283284```tsx285const { searchValue, setSearchValue } = useStore(286 useShallow((state) => ({287 searchValue: state.searchValue,288 setSearchValue: state.setSearchValue,289 })),290)291```292293Alternatively, subscribe to each value with its own selector — there is no wrapper object to recreate:294295```tsx296const searchValue = useStore((state) => state.searchValue)297const setSearchValue = useStore((state) => state.setSearchValue)298```299300See [Requiring stable selector outputs](../migrations/migrating-to-v5.md#requiring-stable-selector-outputs) in the v5 migration guide for the underlying behavior change.