Why React.memo is important?
React.memo is a high order component that takes a component and returns a new component. The main purpose of this is to increase performance by avoiding unnecessary rendering. We’ll discuss more important details about React.memo in below paragraphs
I am going to explain React.memo behavior using example, then it will be very easy for you to understand this concept.
First, let’s take an example of simple code and do a dry run
There are 3 components will be created in our example. Component A is the parent component and B and C are child components.
Before going to describe the parent component, child components will be discussed first. As you can see, Component B takes the count value as its parameter and Component C takes the name value as its parameter.
In Component A, there is a state object is defined in line:5 and I am not going to talk about useState hook since I hope that you all are having the basic knowledge. Follow this video to get more information about useState
setInterval method will continuously update the count value after every 10 seconds but not the value of the name. But when you run this code, you will notice that every time when the count is updated, Both Component B and C will be re-rendered. (Check the console logs)
Why Component C is re-rendered?
That is because when the state changed in parent components sub-components will also re-render as well. This is why React.memo is used to avoid unnecessary rendering. Let’s discuss the importance of React.memo and the way it is implemented.
The logic behind the React.memo
React memo will allow to re-render, only if the previous props and current props are different. So basically what this method does is compare props values before rendering the component.
let’s wrap Component C with React.memo and run the code
Now if you run the code and check the console logs, you will see that only Component B will be re-rendered and Component C won’t render. That is because Component C only takes the name parameter and that doesn’t change when the count is increased. So there isn’t any difference between previous prop value and the new prop value in Component C, because of that Component C won’t be rendered.
This is all you need to know about React.memo. I hope you got some knowledge from this. Thank you for reading this. Don’t hesitate to ask, If you have any questions regarding this.