Skip to main content

Importance of React.memo

React.memo is a high order component that takes a component and returns a new component. Main purpose of this is to improve performance by avoiding unnecessary rendering. More details about React.memo will be discussed below.

React.memo behaviour will be explained with an example for the ease of understanding.


First, let's take a piece of simple code and do a dry run.


Component Hierarchy
                     Component hierarchy


There are 3 components that will be created in this example. Component A is the parent component and B and C are child components.


Example code



Child components will be discussed first, before the parent component. 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 defined in line:5. useState hook will not be explained here as I assume you all have a basic knowledge on it. You can watch this video to get more information about useState.

setInterval method will continuously update the count value every 10 seconds but not the value of the name. However, 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 is Component C re-rendered?

Component C is re-rendered because when the state changed its 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 React.memo

React.memo will allow the re-rendering, only if the previous props and current props are different. Basically, what this method does is comparing 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. 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. Hence there is no difference between previous prop value and the new prop value in Component C, and due to that, Component C won’t be rendered.

This is all you need to know about React.memo. I hope you gained some knowledge from this. If you have any questions regarding this, please post as a comment below.



© 2021 Creative Software. All Rights Reserved | Privacy | Terms of Use