0

I am new to React, and in my app, I have to optimize it to avoid unnecessary rerendering. So far, I have found that there is shouldComponentUpdate for React.Component and React.PureComponent, and memo for functional components. I am using memo as I want to use functional components. However, I found that it does not always avoid rerendering in certain scenarios. I have created an example in this sandbox: https://codesandbox.io/s/infallible-tristan-kfrwmh?file=/test-rendering.tsx

In the example, I have two types of components: ParentClassComponent and ParentFunctionalComponent. Both of them have two buttons that use memo. One button uses an arrow function to update the count, while the other uses a regular function. Clicking those buttons will show log messages in console to indicate if rerendering is triggered.

Through my experiment, I have concluded that memo only works as expected for class components and arrow functions. I am not sure why this is the case. My assumption is that the arrow function is bound to the instance of the class component, so when ParentClassComponent needs to rerender, it just calls the render() function. As a result, when passing the function to children, it still refers to the same function. On the other hand, ParentFunctionalComponent gets called during rerendering, so functions are created again regardless of whether they are arrow functions or functions inside the component.

I would like to know how to pass a function (or arrow function) in ParentFunctionalComponent so that the memoized children can avoid unnecessary rerendering. Is this possible?

Arst
  • 3,098
  • 1
  • 35
  • 42

0 Answers0