Skip to content

React.memo

React.memo

React.memo is a HOC that help optimize functional components by preventing unnecessary re-renders. By default it performs shallow comparison of the component's props.

Normally when the parent re-renders the children components re-render as well.

js
function Header({title, userName}) {
	return (
		<>
			<Title title={title} />
			<User userName={userName} />
		</>
	);
}

function Title({ title }) {
	return <h1>{title}</h1>
}

The <Title /> component will re-render every time the userName prop changes.

If we wrap the component with React.memo , the <Title /> component will now only re-renders if the title prop changes:

js
import { memo } from 'React';
const Title = memo(function Title({ title }) {
	return <h1>{title}</h1>
});

In some use cases, shallow comparisons may not be sufficient. In those cases a function can be passed as the second argument to React.memo.

js
import { isEqual } from 'lodash';

const DataTable = memo(function DataTable({ dataPoints, options }) {
	// ...
}, arePropsEqual);  
  
function arePropsEqual(oldProps, newProps) {  
	return isEqual(oldProps.dataPoints, newProps.dataPoints);
}

In this case the DataTable will only re-renders when the dataPoints prop changes.

Note: make sure to use the Performance tab in the browser to measure whether the arePropsEqual functions save times compare to just re-rendering the component.