EasyPerformance📖 Theory Question

What is React.memo and when does it actually prevent re-renders?

💡

Hint

Shallow prop comparison — skips re-render if props are shallowly equal. Useless without stable prop references.

Full Answer

React.memo wraps a component and shallowly compares old and new props. Skips the re-render if props haven't changed.

const ExpensiveList = React.memo(function ExpensiveList({ items, onSelect }) {
  // Only re-renders if items or onSelect reference changes
  return items.map(item => );
});

// ─── For memo to work, props must be stable references ────────────────────
function Parent() {
  const [count, setCount] = useState(0);

  // ❌ New array reference every render → memo useless
  const items = [{ id: 1 }, { id: 2 }];
  const onSelect = (id) => console.log(id);

  // ✅ Stable references
  const items = useMemo(() => [{ id: 1 }, { id: 2 }], []);
  const onSelect = useCallback((id) => console.log(id), []);

  return ;
}

Custom comparison:

const List = React.memo(Component, (prev, next) => {
  return prev.items.length === next.items.length; // custom equality
});
💡 React.memo is not free — it adds a comparison on every render. Only add it to components that are measurably slow or render very frequently. Profile with React DevTools Profiler first.

More Performance Questions

EasyWhat is code splitting and lazy loading in React?MediumWhat is virtualization (windowing) and when do you need it?MediumWhat causes unnecessary re-renders and how do you diagnose them?MediumWhat is the React Profiler and how do you use it to diagnose performance issues?

Practice this in a timed sprint →

5 free questions, no signup required

⚡ Start Sprint