Loading

Quipoin Menu

Learn • Practice • Grow

react / React.memo
tutorial

React.memo

In React, when a parent component re-renders, all its children re-render by default. This can cause performance issues if the child components are expensive to render or if they re-render unnecessarily. **React.memo** is a higher-order component that helps prevent unnecessary re-renders.

What is React.memo?

React.memo is a higher-order component that memoizes a component. It means that if the component's props haven't changed, React will skip rendering the component and reuse the last rendered result. This is a performance optimization for functional components.

Think of React.memo as a guard that checks if props have changed. If they haven't, it says, "Nothing new here, let's skip rendering."

Basic Usage
import React, { memo } from 'react';

<!-- Regular component that re-renders often -->
const ExpensiveComponent = ({ name, count }) => {
  console.log('ExpensiveComponent rendered');
  return (
    <div>
      <h3>Hello, {name}!</h3>
      <p>Count: {count}</p>
    </div>
  );
};

<!-- Memoized version -- only re-renders if name or count change -->
const MemoizedComponent = memo(ExpensiveComponent);

function Parent() {
  const [count, setCount] = useState(0);
  const [other, setOther] = useState(0);

  return (
    <div>
      <MemoizedComponent name="John" count={count} />
      <button onClick={() => setCount(count + 1)}>Increment Count</button>
      <button onClick={() => setOther(other + 1)}>Increment Other ({other})</button>
    </div>
  );
}

In this example, `MemoizedComponent` will only re-render when `count` changes. Clicking the "Increment Other" button won't cause it to re-render.

Custom Comparison Function

By default, React.memo does a shallow comparison of props. You can provide a custom comparison function as the second argument.
const MemoizedComponent = memo(
  ExpensiveComponent,
  (prevProps, nextProps) => {
    <!-- Return true if props are equal (don't re-render), false if they changed -->
    return prevProps.name === nextProps.name && prevProps.count === nextProps.count;
  }
);

When to Use React.memo
  • Pure functional components that render often with the same props.
  • Components that are expensive to render (large lists, complex UI).
  • Components that receive props that rarely change.

When NOT to Use React.memo
  • Components that always receive different props.
  • Simple, cheap-to-render components (the memo check itself has a cost).

Two Minute Drill

  • React.memo is a higher-order component that prevents unnecessary re-renders.
  • It performs a shallow comparison of props if they haven't changed, it skips rendering.
  • Use it for expensive components that render often with the same props.
  • You can provide a custom comparison function for complex prop structures.
  • Don't overuse it the memoization itself has a performance cost.

Need more clarification?

Drop us an email at career@quipoinfotech.com