【React.memo】
The second argument of React.memo seems safer not to use ?

TiShow
2 min readMar 28, 2023

React.memo to memoize the function component, but there is a second argument that is not used very often (and that you may not want to use for reasons discussed below).

I have the opportunity to use a second argument of React.memo several times these days. Therefore, I note this article.

What is the second argument of React.memo ?

  • The second argument of React.memo is a function that compares whether the previous props and the new props are “the same
  • This tends to cause bugs because the comparison decision and the point of use are far apart.
  • It would be easier to pass only necessary values to lower level components that are memoized.

About the second argument

You can pass a function like function areEqual(prevProps, nextProps) as the second argument to React.memo.
This function will be called when you try to render the component after memoization, and if it returns true, you do not have to render it.

Functional Notes.

  • The class component shouldComponentUpdate, as the name implies, returns true if you want to update it, but the opposite is true for React.memo.
  • You cannot check the state (if you rewrite the state created by React.useState, the component will be redrawn).
  • This is only an optimization tip, and you should not write code that relies on “if it returns true, it will not be rendered”.

Alternative plan

Fortunately, nearly equivalent performance can also be achieved with regular React.memo.

Cut out the components

There is a way to cut out the lower-level components and apply React.memo to them to apply memoization at an appropriate level of granularity. For example, even if there is one <select>, there are many <option> in it, and if it is redrawn as it is, the contents will also be checked. There aren’t many operations where the is switched, so if you cut out the <select> and its contents into a memoized component, you can reduce redrawing. Furthermore, even if the entire original component required redrawing, there may be cases where redrawing is not required if only a portion of the component is cut out, so processing can be further reduced.

Conclusion

In this case, we have seen that React.memo can be used to avoid unnecessary re-rendering when there is no change in the value of the props received by a component.

This makes us want to use React.memo for various components, but memoization is also costly. Therefore, when tuning performance, it is a good idea to carefully compare the cost of memoization with the cost of recalculation of components before implementation.

--

--

TiShow

80% is the creation, the rest is depression. Developer and Data scientist. Looking for Physics Ph.D Twitter: @_t_i_show