Become a member
to unlock all features

Level Up!

Access all courses & lessons on egghead today and lock-in your price for life.


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

    Tomasz ŁakomyTomasz Łakomy

    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.



    Become a Member to view code

    You must be a Member to view code

    Access all courses and lessons, track your progress, gain confidence and expertise.

    Become a Member
    and unlock code for this lesson




    Instructor: 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.

    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.

    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.

    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.

    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.