如果我不需要任何道具,我应该用 React.memo() 包装我的所有组件吗? [英] Should I wrap all my components with React.memo() if it is not expecting any props?

查看:36
本文介绍了如果我不需要任何道具,我应该用 React.memo() 包装我的所有组件吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

虽然很明显为什么 React 默认不会对其所有功能组件执行 React.memo,但我们应该在需要时自己包装我们的功能组件.

While it is obvious why React does not perform React.memo to all its functional component by default, and we should ourself wrap our functional components as and when needed.

就我而言,我有一个大型 React 项目,其结构如下:

In my case, I have a big react project with a structure like this:

const MyBigApp = () => {
  const shouldShowX = useSelector(getShouldShowX);
  const shouldShowY = useSelector(getShouldShowY);
  // Many more selectors

  return (
    <>
      {shouldShowX && <ComplexComponentX />}
      {shouldShowY && <ComplexComponentY />}
      {/* many more components based on different selectors like above */}
   </>
  );
};

我的所有业务逻辑都在 redux 中,组件在内部使用 useSelector 从商店获取数据.

All my business logic is inside redux and the components use useSelector internally to get data from the store.

React.memo 包装我的所有子组件是否有意义,因为根级别的任何选择器的更改都会导致我的整个应用程序重新渲染?

Does it make sense to wrap all my child components with React.memo, as a change in any selector at root level causes my entire app to re-render?

之前使用 connect 我们会自动获得一个记忆组件,它比较自定义道具和存储值作为道具传递给组件,所以我们现在应该手动总是React.memo 在没有收到任何 props 的组件中使用 useSelector 时?

Earlier with connect we were automatically getting a memoized component which was comparing custom props and store value passed as props to the component, so should we now manually always do React.memo while using useSelector in a component not receiving any props?

推荐答案

我认为你应该考虑对那些不接受任何 props 的子组件使用 React.memo.我强烈推荐这篇文章:https://dmitripavlutin.com/use-react-memo-wisely/

I would argue that you should consider using React.memo for those child components that don't accept any props. I highly recommend this article: https://dmitripavlutin.com/use-react-memo-wisely/

2.1 组件渲染通常使用相同的 props
在 React.memo() 中包装组件的最佳情况是您期望函数式经常使用相同的 props 渲染的组件.

2.1 Component renders often with the same props
The best case of wrapping a component in React.memo() is when you expect the functional component to render often and usually with the same props.

由于您询问的组件不接受任何道具,这意味着道具永远不会改变.因此,使用 React.memo 可以避免渲染周期是理所当然的.请注意同一篇文章中的这一重要警告:

Since the components you're asking about don't accept any props, that means the props will never change. Therefore, it stands to reason that using React.memo could avoid render cycles. Note this important caveat from the same article:

5.React.memo() 是性能提示
严格来说,React 使用记忆作为性能提示.

5. React.memo() is a performance hint
Strictly, React uses memoization as a performance hint.

虽然在大多数情况下 React 避免渲染记忆化组件,你不应该指望它来阻止渲染.

While in most situations React avoids rendering a memoized component, you shouldn’t count on that to prevent rendering.

这篇关于如果我不需要任何道具,我应该用 React.memo() 包装我的所有组件吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆