优化react组件非必要的重新渲染

重新渲染的起因:

  • 组件的state变化
  • 父组件重新渲染,导致子组件重新渲染
  • 组件使用context,provider的value发生变化时
  • hooks变化
    • hooks内的状态更改将触发不可避免的宿主重复渲染
    • 如果hooks使用了 Context 并且 Context 的值发生了变化,它会触发一个不可避免的重复渲染

渲染优化:

  • 使用memo、useMemo缓存组件
  • 向下移动状态。当前组件很重,但是有个小弹窗是当前组件控制的状态,会导致当前组件重渲染,将控制弹窗的state抽离到一个新组件中,很重的父组件就不会重渲染
  • 将组件抽离为props的children,children在子组件中不会重渲染
  • 将组件作为props传递到子组件,子组件更新不会影响到这个props组件
  • effect的依赖中有引用类型数据(对象,数组,函数等),应对这些依赖进行useMemo,useCallback
  • context不在根组件,其祖先更新会导致其更新进而导致使用该context的组件更新,应对该context使用useMemo记忆
  • 使用多层的context,外层的context变化不会影响到内层的context(同上述children)

子组件使用useContext导致的重渲染

// value是个复杂类型的对象,父组件的重渲染会导致重新生成{mode}
const ThemeContext = React.createContext<Theme>({ mode: 'light' });
const useTheme = () => {
  return useContext(ThemeContext);
};
// before:
// 父组件
const [mode, setMode] = useState<Mode>("light");
return (
    <ThemeContext.Provider value={{ mode }}>
      // 这里有个计数器点击+1
      // 这里有个按钮可以切换主题模式
    </ThemeContext.Provider>
  );
const Item = ({ country }: { country: Country }) => {
    // 父组件计数器+1,这里每次会是个新对象,导致重渲染
    const { mode } = useTheme();
    const className = `country-item ${mode === "dark" ? "dark" : ""}`;
    // the rest is the same
}

// after:
const [mode, setMode] = useState<Mode>("light");
// memoising the object! 缓存对象
  const theme = useMemo(() => ({ mode }), [mode]);
return (
    <ThemeContext.Provider value={theme}>
      <button onClick={() => setMode(mode === 'light' ? 'dark' : 'light')}>Toggle theme</button>
      // 这里有个计数器,可以点击+1
      // 这里有个按钮可以切换主题模式
    </ThemeContext.Provider>
  )
// 子组件
const Item = ({ country }: { country: Country }) => {
    // 父组件计数器+1,这里每次是个同一个theme对象,不会重渲染
    // 切换主题会导致子组件重新渲染
    const { mode } = useTheme();
    const className = `country-item ${mode === "dark" ? "dark" : ""}`;
    // the rest is the same
}

React.memo,配合useCallback将组件缓存

// props中的属性全部使用useMemo进行缓存,MovingComponent 的重渲染不会导致ChildComponent 的重渲染
// 如果props中有函数参数,在父组件中应使用useCallback包裹,以保持父组件每次重渲染时,传递给子组件的函数引用地址一致
// 如果子组件中接收的children和props是组件,则这些组件都需要memo,子组件才不会重渲染
const ChildComponent = (props) {
  ...
  return (
      <div onClick={props.onClick}>{props.a}</div>
  )
}
export default React.memo(ChildComponent)

const MovingComponent = () => {
const [state, setState] = useState({ x: 100, y: 100 });
const onClick = useCallback(() => {
    console.log('xxx')
}, [])
return (
  <div
    onMouseMove={(e) => setState({ x: e.clientX - 20, y: e.clientY - 20 })}
    style={{ left: state.x, top: state.y }}
  >
    // MovingComponent的重渲染不会导致ChildComponent 的重渲染
    <ChildComponent a={111} onClick={onClick} />
  </div>
);
};


抽离为children,以避免重渲染

# 鼠标移动后,MovingComponent 会重渲染,导致子组件ChildComponent 重渲染,如果后者很“重”,将导致性能问题
const MovingComponent = () => {
  const [state, setState] = useState({ x: 100, y: 100 });

  return (
    <div
      // when the mouse moves inside this component, update the state
      onMouseMove={(e) => setState({ x: e.clientX - 20, y: e.clientY - 20 })}
      // use this state right away - the component will follow mouse movements
      style={{ left: state.x, top: state.y }}
    >
      <ChildComponent />
    </div>
  );
};
// ChildComponent 通过children 传递,MovingComponent 的重渲染不会导致ChildComponent 重渲染,
// 因为ChildComponent 隶属于组件SomeOutsideComponent,组件作为children传递不会重渲染,因为它是props,
// 它在SomeOutsideComponent 组件中已经创建完毕,已经调用过React.createElement了
const MovingComponent = ({ children }) => {
  const [state, setState] = useState({ x: 100, y: 100 });

  return (
    <div onMouseMove={(e) => setState({ x: e.clientX - 20, y: e.clientY - 20 })} style={{ left: state.x, top: state.y }}>
      // children now will not be re-rendered
      {children}
    </div>
  );
};

const SomeOutsideComponent = () => {
  return (
    <MovingComponent>
      <ChildComponent />
    </MovingComponent>
  );
};

Mystery 1:为什么通过props传递一个组件给子组件,子组件重渲染不会使传递的组件重渲染?

why components that are passed as props don’t re-render?
Answer 1: “children” is a <ChildComponent /> element that is created in SomeOutsideComponent. When MovingComponent re-renders because of its state change, its props stay the same. Therefore any Element (i.e. definition object) that comes from props won’t be re-created, and therefore re-renders of those components won’t happen.

children即<ChildComponent />组件是在SomeOutsideComponent组件中创建的,MovingComponent state变化引起重渲染,但MovingComponent 的props与上次一样没有变化,所以任何来自props的组件(或者自定义对象)不会在MovingComponent 重渲染期间重新创建,自然也不会发生重渲染

Mystery 2: 为什么将props.children通过一个函数传递,会导致重渲染?

if children are passed as a render function, they start re-rendering. Why?

const MovingComponent = ({ children }) => {
  // this will trigger re-render
  const [state, setState] = useState();
  return (
    <div ///...
    >
      <!-- those will re-render because of the state change -->
      {children()}
    </div>
  );
};

const SomeOutsideComponent = () => {
  return (
    <MovingComponent>
      {() => <ChildComponent />}
    </MovingComponent>
  )
}

Answer 2:In this case “children” are a function, and the Element (definition object) is the result of calling this function. We call this function inside MovingComponent, i.e. we will call it on every re-render. Therefore on every re-render, we will re-create the definition object <ChildComponent />, which as a result will trigger ChildComponent’s re-render.

在这个例子中,children是个函数,并且childComponent是调用该函数的结果,MovingComponent的每次重渲染都会在组件内部调用这个函数,返回一个新的结果,所以MovingComponent的每次重渲染会导致childComponent的重渲染

Mystery 3: MovingComponentMemo使用memo,为什么没有阻止由于SomeOutsideComponent 重渲染导致ChildComponent 的重渲染

// wrapping MovingComponent in memo to prevent it from re-rendering
const MovingComponentMemo = React.memo(MovingComponent);

const SomeOutsideComponent = () => {
  // trigger re-renders here with state
  const [state, setState] = useState();

  return (
    <MovingComponentMemo>
      <!-- ChildComponent will re-render when SomeOutsideComponent re-renders -->
      <ChildComponent />
    </MovingComponentMemo>
  )
}

const MovingComponent = ({children}) => <>{children}</>

Answer 3:因为SomeOutsideComponent 的每次重渲染都重新创建了ChildComponent (是个对象),MovingComponentMemo会检查props是否变动,即检查props.children,因为ChildComponent 是重新生成的,与之前的不相等(2个对象的地址不相等),所以会触发重渲染;如果将ChildComponent 使用memo包裹,则MovingComponent的重渲染不会导致ChildComponent 重渲染,因为MovingComponent检查发现这个props与之前的相等

Mystery 4: 将Mystery 2中的函数使用useCallback包裹,还是阻止不了重渲染?

when passing children as a function, why memoizing this function doesn’t work?

const SomeOutsideComponent = () => {
  // trigger re-renders here with state
  const [state, setState] = useState();

  // this memoization doesn't prevent re-renders of ChildComponent
  const child = useCallback(() => <ChildComponent />, []);

  return <MovingComponent>{child}</MovingComponent>;
};

const MovingComponent = ({ children }) => {
  // this will trigger re-render
  const [state, setState] = useState();
  return (
    <div ///...
    >
      <!-- those will re-render because of the state change -->
      {children()}
    </div>
  );
};
child函数被记忆,但是它的返回结果(<ChildComponent />)没有被记忆,同一个函数每次都会执行React.createElement,即重渲染

参考
https://www.developerway.com/posts/react-elements-children-parents
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容