Use React.memo to avoid unnecessary re-renders in React functional components

Tomasz Łakomy
InstructorTomasz Łakomy
Share this video with your friends

Social Share Links

Send Tweet

Class components can bail out from rendering when their input props are the same using PureComponent or shouldComponentUpdate. Since React 16.6 you can do the same with function components by wrapping them in React.memo.

Instructor: [00:00] We have a very simple React application. It consists of two elements. The first one is a div displaying the current count. By default, it's set to zero. We also have a button, which allows us to increase the counter when we click it. Let's say that we would like to add a header, which is going to be a stateless functional component.

[00:19] I'm going to set a text prop that is going to return a div displaying the text provided in this prop. We are also going to add a console.log to check how many times this component has been rendered. Save that, and use our header over here.

[00:35] I'm going to put a header, and also provide a text prop. set to header. Let me format that, and now, let's take a look inside of the dev tools. You can see by default, this component has been rendered once, but if I click the button, even though the text header hasn't changed at all, we are still rendering this component over and over again.

[00:59] We can fix this. To fix this, import a memo higher order component from React. Next, wrap the stateless functional component inside of the memo component. The result is as follows. Now, if I click the button, there will be no additional renders.

[01:16] The reason it works because React memo shallowly compares the probes passed into the stateless functional component. The props haven't changed. For instance, in this case, when the text is always set to header, it will not render the component again, even though the state of the parent component has changed.