• 简体中文
  • 使用 useShallow 避免重新渲染

    当你需要订阅 store 中计算得出的状态时,推荐的做法是使用选择器。

    如果输出发生了变化(依据 Object.is 判断),这个计算选择器就会触发重新渲染。

    在这种情况下,如果计算值在浅比较下始终与上一次的值相等,你可能希望使用 useShallow 来避免重新渲染。

    示例

    我们有一个 store,它为每只小熊关联一份餐食,而我们要渲染它们的名字。

    import { create } from 'zustand'
    
    const useMeals = create(() => ({
      papaBear: 'large porridge-pot',
      mamaBear: 'middle-size porridge pot',
      littleBear: 'A little, small, wee pot',
    }))
    
    export const BearNames = () => {
      const names = useMeals((state) => Object.keys(state))
    
      return <div>{names.join(', ')}</div>
    }

    现在熊爸爸想换成披萨:

    useMeals.setState({
      papaBear: 'a large pizza',
    })

    尽管 names 的实际输出按浅比较并未改变,这一变更仍然导致 BearNames 重新渲染。

    我们可以用 useShallow 解决这个问题!

    import { create } from 'zustand'
    import { useShallow } from 'zustand/react/shallow'
    
    const useMeals = create(() => ({
      papaBear: 'large porridge-pot',
      mamaBear: 'middle-size porridge pot',
      littleBear: 'A little, small, wee pot',
    }))
    
    export const BearNames = () => {
      const names = useMeals(useShallow((state) => Object.keys(state)))
    
      return <div>{names.join(', ')}</div>
    }

    现在它们都可以点其他餐食,而不会导致我们的 BearNames 组件发生不必要的重新渲染。