Re-rendering

⭐ Interview Importance: MEDIUM
⏱️ Revision Time: 2 min

Re-rendering

In React, a “re-render” occurs when React calls a component function again after its initial mount.

Why do components re-render?

A component will inherently re-render for one of three reasons:

  1. Its local state changed: A component called its own state setter function (e.g., setCount).
  2. Its parent component re-rendered: When a parent re-renders, React recursively re-renders all of its children by default.
  3. A Context it consumes changed: If a component uses useContext(MyContext), and the value provided to MyContext.Provider changes, the consuming component will re-render.

Note: Changes to props do not inherently cause a re-render. Rather, props change because the parent re-rendered, and it’s the parent’s re-render that causes the child to re-render. If a parent re-renders but passes the exact same props to a child, the child will still re-render by default.

Unnecessary Re-renders

An “unnecessary re-render” is when a component goes through the Render Phase, but its output (the JSX) doesn’t change, meaning React does nothing during the Commit Phase.

While the Commit Phase (touching the actual DOM) is the slowest part of React, the Render Phase (calling the JavaScript functions) can also become a bottleneck if you have a massive component tree or expensive calculations inside your components.

Preventing Re-renders

If a child component is slow to render, you can wrap it in React.memo().

React.memo is a Higher-Order Component that tells React: “Skip the Render Phase for this component if its props haven’t changed since the last render.”

import { memo } from 'react';

// This component will ONLY re-render if 'title' or 'content' changes.
// It will NOT re-render just because its parent re-rendered.
const ExpensivePost = memo(function ExpensivePost({ title, content }) {
  // ... heavy rendering logic
});

The “Prop Drilling” Re-render Myth

A common misconception is that “prop drilling” (passing a prop down multiple levels) causes intermediate components to re-render.

Intermediate components re-render because their parent re-rendered, not because a prop passed through them changed. If you use Context to bypass intermediate components, those intermediate components will still re-render when the root component updates its state, unless they are wrapped in React.memo().

Interview Questions

Q: What are the primary triggers that cause a React component to re-render?
A:

  1. A state variable within the component changes.
  2. The component’s parent re-renders (this unconditionally forces all children to re-render, unless they are memoized).
  3. A Context value that the component is subscribed to changes.
  4. A hook the component uses triggers a state/context update.
    (Note: A prop change only causes a re-render because the parent had to re-render to pass the new prop in the first place).