What is React.memo and when should you use it

In the latest version of React (16.6.0) there is a new API React.memo. This API is a higher order component and is similar to React.PureComponent.

 

Why memo?

The name is a derivate from the word memoize, and according to Wikipedia:

In computing, memoization is an optimization technique used primarily to speed up computer programs by storing the results of expensive function calls and returning the cached result when the same inputs occur again.

 

What is the difference between React.PureComponent and React.memo?

The difference between these 2 APIs is that React.PureComponent is used for class components and React.memo is used for function components.

 

Example code

  
  
const MyComponent = React.memo(function (props) { });
  

By default, React.memo() performs a shallow equality check on the current props and nextProps objects only. Because React.PureComponent is used for class components, it compares both the props and state. It does this by iterating on the keys of the objects being compared and returning true when the values of a key in each object are not strictly equal.

If you need something more advanced, you can also pass a comparison function as the second parameter to React.memo():

  
  
const MyComponent = React.memo(function (props) { }, (prevProps, nextProps) => {
  // Your check here
});
  

Since React.memo() is a higher order component, you can also use it to wrap a functional component you already have.

  
  
const PersonComponent = props => <div>My name is. {props.name}!</div>;

const MemoizedPersonComponent = React.memo(PersonComponent);
  

Andy

Front-end Engineer & Designer based in Dublin currently working @IBM.
I write about: Javascript, HTML, CSS, React JS, React Native and UI/UX Design.

Add comment