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 the below paragraphs
I will 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, a state object is defined in line:5, and I will not talk about the useState hook since I hope that you all are having the basic knowledge. Follow this video to get more information about useState https://www.youtube.com/watch?v=9xhKH43llhU
setInterval method will continuously update the count value after every 10 seconds but not the name's value. But when you run this code, you will notice that whenever the count is updated, Both Component B and C will be re-rendered. (Check the console logs)
Why is Component C 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
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. Component C only takes the name parameter, which doesn’t change when the count is increased. So there isn’t any difference between the 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.
If you like this post, you can read more articles on my personal blog devpubba.com.