Learn how to use useShallow to prevent unnecessary re-renders when working with computed state
When you need to subscribe to a computed state from a store, the recommended way is to use a selector. However, the computed selector will cause a re-render if the output has changed according to Object.is.In cases where the computed value is always shallow equal to the previous one, you can use useShallow to avoid unnecessary re-renders.
This change causes BearNames to re-render even though the actual output of names has not changed according to shallow equality. The array ['papaBear', 'mamaBear', 'littleBear'] is recreated with a new reference each time.
Now the bears can all order different meals without causing unnecessary re-renders of the BearNames component. The component only re-renders when the keys actually change.
// Without useShallow - re-renders on any state changeconst items = useStore((state) => state.items.map(item => item.id))// With useShallow - only re-renders when IDs actually changeconst items = useStore(useShallow((state) => state.items.map(item => item.id)))
// Without useShallow - re-renders on any state changeconst user = useStore((state) => ({ name: state.name, email: state.email }))// With useShallow - only re-renders when name or email changesconst user = useStore(useShallow((state) => ({ name: state.name, email: state.email })))
// Without useShallow - re-renders on any state changeconst [name, age] = useStore((state) => [state.name, state.age])// With useShallow - only re-renders when name or age changesconst [name, age] = useStore(useShallow((state) => [state.name, state.age]))
useShallow performs a shallow comparison of the selector result, checking if all values at the first level are equal using Object.is. This is perfect for arrays and objects with primitive values.