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 are debounce and throttle? When do you use each?EasyWhat causes memory leaks in JavaScript and how do you detect them?EasyWhat is the difference between reflow and repaint, and how do you avoid layout thrashing?MediumWhat is lazy loading and code splitting?

Practice this in a timed sprint →

5 free questions, no signup required

⚡ Start Sprint