Tech Insights
Pubudu Gamage
April 28, 2020

Importance of React.memo

Importance of React.memo

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

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

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

                    Component hierarchy

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

Example code

view rawcomponentA.js hostedwith ❤ by GitHub

Child components will be discussed first, before the parent component.As you can see, Component B takes the count value as itsparameter and Component C takes the name value as its parameter.

In Component A, there is a state object defined in line:5. useState hookwill not be explained here as I assume you all have a basic knowledge on it.You can watch this video to getmore information about useState.

setInterval method will continuously update the count value every 10seconds but not the value of the name. However, when you run this code, youwill notice that every time when the count is updated, both Component B and Cwill be re-rendered. (Check the console logs)

Whyis Component C re-rendered?

Component C is re-rendered because when the state changed its parentcomponents, sub-components will also re-render as well. This is why React.memois used to avoid unnecessary rendering.

Let's discuss the importance of React.memo and the way it isimplemented.

Thelogic behind React.memo

React.memo will allow the re-rendering, only if the previous props andcurrent props are different. Basically, what this method does is comparingprops values before rendering the component.

Let's wrap Component C with React.memo and run the code

view rawcomponentB.js hostedwith ❤ by GitHub

Now if you run the code and check the console logs, you will see thatonly Component B will be re-rendered. Component C won’t render. That is becauseComponent C only takes the name parameter and that doesn’t change when thecount is increased. Hence there is no difference between previous prop valueand the new prop value in Component C, and due to that, Component C won’t berendered.

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