CodeBlanks Logo Icon CodeBlanks

What is React.memo?

Learn to wrap a component with React.memo so it skips renders when props are equal.

What is React.memo?

React.memo is a higher-order component that wraps a component and prevents re-render as long as props don't change. Use it as const MemoCard = React.memo(Card);.

When a parent renders, normally all children render too. React.memo does a shallow comparison of props; if equal, it skips the render.

Most common use: big list items, components doing expensive computation. This lesson covers basic usage; the next lesson covers custom comparators.

Wrapping method

React.memo is used in two ways. First, with a variable: const MemoCard = React.memo(function Card({ '{ name }' }) { ... });. Second, with export: export default React.memo(Card);.

The wrapped component behaves the same as the original; it just adds a render-skip layer. When props don't change, React reuses the previous result.

Two cautions: wrapping every component hurts performance (shallow comparison also costs). Also, without useCallback/useMemo, new prop references always look different, so memo doesn't work.

Practice Write MemoCard

Complete the skeleton. Write a component called Card; take ({ '{ name }' }) and return <div><p>{ '{ name }' }</p></div>. Then wrap with const MemoCard = React.memo(Card);. Export MemoCard.

Starter code

App.jsx
import { memo } from "react";

// Write Card and MemoCard here

Sample solution

App.jsx
import { memo } from "react";

function Card({ name }) {
  return (
    <div>
      <p>{name}</p>
    </div>
  );
}

const MemoCard = memo(Card);

export default MemoCard;

Questions and answers

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

1 What does React.memo prevent?

  • useEffect
  • Needless renders Correct answer
  • CSS changes
  • useState

Explanation: React.memo prevents needless renders.

2 Comparison

Question
React.memo by default does ____ comparison.
Answer
React.memo by default does shallow comparison.

Explanation: Does shallow comparison.

3 Match the React.memo steps

Term Meaning
React.memo wraps
shallow shallow
prop equal skips
useCallback stabilizes

All lessons in Intermediate