Why a component re-rendered

The one-page summary of the lesson Why it re-rendered. It states the answers, so if you want them to stick, play the lesson first: it makes you predict before it explains.

The points

  • A component renders when its own state changes, or when its parent renders.
  • By default, a component that renders renders all of its children, and theirs.
  • Rendering is React calling your components; at the commit React changes only the DOM nodes that differ.
  • memo skips a render only if every prop is the same as last time, compared with Object.is.
  • An inline arrow, object or array in JSX is a new value on every render, so it defeats memo.
  • A memoized component still renders for its own state or a context it reads.
  • Keep state where it is used: fewer components render, often with no memo at all.

What catches people out

  • memo is a performance optimization, not a guarantee
  • useCallback keeps a function the same between renders; it does not stop the component that defines it from rendering

The wrong idea, and the right one

Often believed: A React component re-renders only when its props change, so wrapping a component in memo stops extra renders.

What really happens: A component renders when its state changes or its parent renders. memo skips a render only when every prop is the same object as last time (Object.is), so new functions or objects defeat it. Keeping state where it is used renders less.

Step by step

  1. Mei's slow inbox. Before guessing why something is slow, count what renders.
  2. One key. Commit to a number before you look.
  3. Who renders whom. Components form a tree: a component renders the components it returns.
  4. One key, traced. A state change renders its owner, and by default every component under it.
  5. Render, then commit. Rendering is calling components; React changes only the DOM nodes that differ.
  6. The agent's memo. memo compares props; it does not move state.
  7. Memo sees new props. An inline function is a new prop every render, so memo cannot skip.
  8. Move the state down. State kept where it is used renders only what uses it.
  9. It keeps up. Fix where the state lives, not the components that render because of it.
  10. The rule. State or parent renders a component; memo needs the same props; keep state low.

Sources

Play the lesson: Why it re-rendered