Is it a good idea to memoize all of my react components?

后端 未结 2 1992
自闭症患者
自闭症患者 2021-01-13 14:13

I\'ve recently decided to refresh on react\'s documentation and came across https://reactjs.org/docs/react-api.html#reactmemo (React.memo).

At first glance it looked

相关标签:
2条回答
  • 2021-01-13 14:51

    No, you shouldn't memoize all your function components by default. You should decide when to do this on a case-by-case basis.

    1. It's only for "pure" function components (as in, without side effects)

    From the documentation:

    If your function component renders the same result given the same props, you can wrap it in a call to React.memo for a performance boost in some cases by memoizing the result.

    Imagine that you add some side effect to your function component, for example, reading the current time from Date.now(). The component will work as expected the first time it's called with certain props, but the next time it's called with those same props, the old time will be used. This can lead to confusing bugs.

    2. Not all pure function components will benefit from memoization

    For example, if it's unlikely a component will ever be called with the same props, then memoizing the result will likely lead to worse performance. After all, memoization is just storing the result of a function call to an object, where the key is derived from the input to the function and the value is the result of the function call. Why store this if you'll never use it?

    3. Memoization is more useful for functions that are computation intensive

    If your function component doesn't take many CPU cycles to render, then any performance optimization is likely going to be negligible. But it's now possible to later add side effects to that component, forget that it's being memoized, and waste time fixing the resulting bugs.

    Again, from the docs:

    This method only exists as a performance optimization. Do not rely on it to “prevent” a render, as this can lead to bugs.

    0 讨论(0)
  • 2021-01-13 15:02

    For shorter explanation:

    If React.memo() everything makes React more efficient and optimized, it should be considered as a default behavior, not only an option (like pure function).

    Basically, React.memo() prevents redundant rerenders by comparing the component's previous and current props.

    <Parent>
      <Child />
    </Parent>
    

    Normally, when the Parrent rerenders, the Child rerender as well by default.

    With React.memo(), if the props passed into Child are not changed when Parent rerender, Child does not rerender.

    The question here is: why React knows props passed to Child was not changed in the current rerender ?

    The answer is: React itself has to do a comparison, and it is the cost of React.memo()

    If the time to comparison > the time to just rerender the whole Child component, it even slows down your app.

    0 讨论(0)
提交回复
热议问题