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
Published 5 years ago
Updated 3 years ago

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.

egghead
egghead
~ a minute ago

Member comments are a way for members to communicate, interact, and ask questions about a lesson.

The instructor or someone from the community might respond to your question Here are a few basic guidelines to commenting on egghead.io

Be on-Topic

Comments are for discussing a lesson. If you're having a general issue with the website functionality, please contact us at support@egghead.io.

Avoid meta-discussion

  • This was great!
  • This was horrible!
  • I didn't like this because it didn't match my skill level.
  • +1 It will likely be deleted as spam.

Code Problems?

Should be accompanied by code! Codesandbox or Stackblitz provide a way to share code and discuss it in context

Details and Context

Vague question? Vague answer. Any details and context you can provide will lure more interesting answers!

Markdown supported.
Become a member to join the discussionEnroll Today