Tutorial

Getting to Grips with React.Memo

Published on August 15, 2019
author

Paul Ryan

Getting to Grips with React.Memo

React.memo gives us the ability of pure components in React but for functional based components rather than class based ones.

memoization is computer science jargon which means caching the result of expensive function calls and returning the cached version when the arguments are the same.

In React terms:

Illustrated React.Memo

We don’t want MyNewComponent re-rendering when the props being passed are the same.

Simple Counter Example

I’ve created the following example in Codesandbox to help cement in your mind how React.memo works.

It’s a simple app that counts the number of times a button is clicked. You can see from the below screenshot we have a banner on top of the page.

Screenshot of the demo App

Imagine the Banner is a UI component that can have different types, in this case you want to use the info type banner so you create your Banner as follows:

<Banner type="info" />

Our CounterComponent looks like this:

class CounterComponent extends Component {
  state = { buttonPressedCount: 0 };
  render() {
    const { buttonPressedCount } = this.state;
    return (
      <div className="new-component">
        <h4>Button Pressed Count: {buttonPressedCount}</h4>
        <button
          onClick={() =>
            this.setState({ buttonPressedCount: buttonPressedCount + 1 })
          }
        >
          Increase Count
        </button>
        <Banner type="info" />
      </div>
    );
  }
}

And our Banner component looks as follows:

const Banner = props => {
  const { type } = props;

  if (type === "info") {
    return <div className="info-banner">I am an info banner</div>;
  }
};

In our CounterComponent, every time we click the button we increase the buttonPressedCount variable which causes a re-render which is what you would expect. The problem with this is that the Banner component also re-renders even though the props being passed to it haven’t changed.

To circumvent this, we use memo which acts like PureComponent in the fact that it will stop re-renders when the props haven’t changed. Our code updated looks like:

const Banner = memo(props => {
  const { type } = props;

  if (type === "info") {
    return <div className="info-banner">I am an info banner</div>;
  }
});

Now our Banner component will only re-render when the props to it have changed.

This is core fundamental idea of React memo.

areEqual

Ok so let’s get a little more advanced and talk about custom equality. By default, memo only does a shallow comparison of props and prop’s objects. You can pass a second argument to indicate a custom equality check:

React.memo(Component, [areEqual(prevProps, nextProps)]);

This is similar to shouldComponentUpdate but the inverse i.e. returning true in shouldComponentUpdate causes another render whereas areEqual is the opposite.

Imagine we had a Person component that accepted a prop person which is an object, we could check if the name is the same.

const areEqual = (prevProps, nextProps) => {
  return (prevProps.name === nextProps.name)
};
React.memo(Person, areEqual);

Conclusion

This is a really nice addition to React, allowing us to use functional components without having the worry about needless re-renders. As always, I hope you learned something good with this post!

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

Learn more about our products

About the authors
Default avatar
Paul Ryan

author

While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.

Still looking for an answer?

Ask a questionSearch for more help

Was this helpful?
 
1 Comments


This textbox defaults to using Markdown to format your answer.

You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!

A real working example in a sandbox using a custom equality function would’ve been nice.

Try DigitalOcean for free

Click below to sign up and get $200 of credit to try our products over 60 days!

Sign up

Join the Tech Talk
Success! Thank you! Please check your email for further details.

Please complete your information!

Become a contributor for community

Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.

DigitalOcean Documentation

Full documentation for every DigitalOcean product.

Resources for startups and SMBs

The Wave has everything you need to know about building a business, from raising funding to marketing your product.

Get our newsletter

Stay up to date by signing up for DigitalOcean’s Infrastructure as a Newsletter.

New accounts only. By submitting your email you agree to our Privacy Policy

The developer cloud

Scale up as you grow — whether you're running one virtual machine or ten thousand.

Get started for free

Sign up and get $200 in credit for your first 60 days with DigitalOcean.*

*This promotional offer applies to new accounts only.