prevent-rerenders-with-use-shallow.md
This file
Path
docs/learn/guides/prevent-rerenders-with-use-shallow.md
63 lines · 1.7 KiB · Markdown
Last changed by
Revamping docs - file restructuring (#3392)Danilo Brittobefore adoption8eae4e9
History of this fileTake it
Revamping docs - file restructuring (#3392)Danilo Brittobefore adoption8eae4e9
lines 1–63why, one step back1---2title: Prevent rerenders with useShallow3nav: 94---56When you need to subscribe to a computed state from a store, the recommended way is to7use a selector.89The computed selector will cause a rerender if the output has changed according to [Object.is](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is?retiredLocale=it).1011In this case you might want to use `useShallow` to avoid a rerender if the computed value is always shallow12equal the previous one.1314## Example1516We have a store that associates to each bear a meal and we want to render their names.1718```js19import { create } from 'zustand'2021const useMeals = create(() => ({22 papaBear: 'large porridge-pot',23 mamaBear: 'middle-size porridge pot',24 littleBear: 'A little, small, wee pot',25}))2627export const BearNames = () => {28 const names = useMeals((state) => Object.keys(state))2930 return <div>{names.join(', ')}</div>31}32```3334Now papa bear wants a pizza instead:3536```js37useMeals.setState({38 papaBear: 'a large pizza',39})40```4142This change causes `BearNames` rerenders even though the actual output of `names` has not changed according to shallow equal.4344We can fix that using `useShallow`!4546```js47import { create } from 'zustand'48import { useShallow } from 'zustand/react/shallow'4950const useMeals = create(() => ({51 papaBear: 'large porridge-pot',52 mamaBear: 'middle-size porridge pot',53 littleBear: 'A little, small, wee pot',54}))5556export const BearNames = () => {57 const names = useMeals(useShallow((state) => Object.keys(state)))5859 return <div>{names.join(', ')}</div>60}61```6263Now they can all order other meals without causing unnecessary rerenders of our `BearNames` component.