CodeBlanks Logo Icon CodeBlanks

React.memo

Learn memoization with React.memo.

What is React.memo?

React.memo wraps a component so it only re-renders when its props change. Even if the parent renders, React keeps the last output when props are the same and skips unnecessary drawing.

It is most useful for pure display components. Writing const MemoCard = React.memo(Card) gives you a wrapped version. Memoizing each row in a fast scrolling list boosts performance. But for tiny components the memo overhead can outweigh the benefit; do not use it everywhere.

Using memo

You pass the component to React.memo; you get a wrapped component back. When the parent renders, this wrapped component shallowly compares the previous props with the next (shallow compare). If they are equal it skips re-rendering.

You can also give a custom comparison function: React.memo(Card, (prev, next) => prev.id === next.id). If the second parameter returns true React skips. This flexibility helps with complex props. The default shallow compare is enough for most cases; add a custom function only when truly needed.

Practice Write a memoized card

A Card component is already defined; it takes a title prop. Create MemoCard with React.memo. Pass the Card function straight to React.memo.

Starter code

App.js
import React from 'react';
import { Text } from 'react-native';

function Card({ title }) {
  return <Text>{title}</Text>;
}

// Create MemoCard with React.memo

Sample solution

App.js
import React from 'react';
import { Text } from 'react-native';

function Card({ title }) {
  return <Text>{title}</Text>;
}

const MemoCard = React.memo(Card);

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 When does React.memo re-render?

App.js
const MemoCard = React.memo(Card);
  • When theme changes
  • Whenever the parent renders
  • Never, even if state changes
  • When props change Correct answer

Explanation: React.memo re-renders when props change.

2 The React.memo call

Question
const MemoCard = React.____(Card);
Answer
const MemoCard = React.memo(Card);

Explanation: React.memo(Card) returns a wrapped component.

3 Match each concept to its role

Term Meaning
React.memo Skips when props same
shallow compare Default behavior
second parameter Custom compare
MemoCard Wrapped component

All lessons in Intermediate