Capítulo 88 de 116

Chapter 88: memo

Core Idea

memo(Component) wraps a component so React skips re-rendering it when its props are shallowly unchanged from the last render — the component-level counterpart to useMemo/useCallback's value/function caching.

Key Concepts

  • Signature: const MemoizedComponent = memo(SomeComponent) — optionally with a second argument, a custom comparison function, if shallow equality isn't the right check for that component's specific props.
  • Shallow comparison: by default, memo compares each prop with Object.is — an object/array/function prop that's recreated fresh every parent render (even with identical contents) still counts as "changed," which is exactly why useMemo/useCallback (Ch 49/59) exist: to give those props stable references so memo's comparison actually succeeds.
  • Only skips re-rendering the memoized component itself, not necessarily its children — if the memoized component re-renders anyway because its own state changed, its children re-render normally regardless of memo.
  • Not a default wrapper: like useMemo, this trades memory/comparison overhead for skipped renders — worth it for components that are expensive to render and receive stable props most of the time, not a blanket "wrap everything" strategy.
  • Custom comparison function: memo(Component, (prevProps, nextProps) => boolean) — return true to skip re-rendering (props considered equal), false to re-render; useful when a prop's deep equality (not just reference equality) is what actually matters.

Code Examples

const Greeting = memo(function Greeting({ name }) {
  return <h1>Hello, {name}</h1>;
});
  • What it demonstrates: Greeting skips re-rendering on parent re-renders where name hasn't changed, without any custom comparison needed since name is a primitive.

Key Takeaways

  1. memo's default shallow comparison only pays off when the props actually stay reference-stable — pair it with useMemo/useCallback upstream for object/array/function props.
  2. Reach for it on components proven (via profiling) to be expensive to re-render, not preemptively on every component.
  3. A custom comparator is an escape hatch for props needing deep-equality checks, not the default recommendation.

Connects To

  • Ch 59 (useMemo) and Ch 49 (useCallback): the reference-stability tools that make this Hook's shallow comparison actually useful.
  • Ch 52 (useDeferredValue): another optimization pattern that specifically relies on memo to skip re-renders while a deferred value lags.