// Tutorial //

Getting to Grips with React.Memo

Published on August 15, 2019
Default avatar
By Paul Ryan
Developer and author at DigitalOcean.
Getting to Grips with React.Memo

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.

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!


Want to learn more? Join the DigitalOcean Community!

Join our DigitalOcean community of over a million developers for free! Get help and share knowledge in our Questions & Answers section, find tutorials and tools that will help you grow as a developer and scale your project or business, and subscribe to topics of interest.

Sign up
About the authors
Default avatar
Paul Ryan

author

Developer and author at DigitalOcean.

Still looking for an answer?

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.