What Causes Re-renders?
Definition
In React, there are only a few specific triggers that cause a component to re-render (re-evaluate its function body). Understanding these is critical for performance optimization.
Explain Like I'm New
A React component is like a very paranoid guard. They only check ID (re-render) if one of three alarms go off: 1. Their own internal state changes. 2. Their boss (parent component) tells them to check ID because the boss is checking IDs. 3. The building intercom (Context API) makes an announcement.
Real World Example
If a `<Clock>` component updates its internal `time` state every second, it re-renders every second. If that clock is inside a `<Dashboard>`, the Dashboard does NOT re-render. But if the Dashboard updates its state, the `<Clock>` is forced to re-render too, just because it's a child.
Common Use Cases
- •Debugging why a component is running too many times
- •Using `React.memo` effectively
Interactive Example
import React, { useState } from "react"; function ChildComponent() { console.log("Child re-rendered!"); return <div className="p-2 border mt-2">I am the child. Watch the console!</div>; } export default function ParentComponent() { const [count, setCount] = useState(0); console.log("Parent re-rendered!"); return ( <div className="p-4 border border-blue-500"> <h2>Parent State Trigger</h2> <button onClick={() => setCount(c => c + 1)}>Update Parent ({count})</button> {/* Even though we pass NO props to the child, it will re-render every time we click the button just because the parent re-rendered! */} <ChildComponent /> </div> ); }
Interview Questions
basic
- What is the most common cause of a re-render?
- Does changing a `useRef` current value cause a re-render?
intermediate
- If a parent component re-renders, what happens to its children?
- Do props changing cause a re-render?
advanced
- If a component consumes a Context, and a completely unrelated part of that Context value changes, does the component re-render?
- What is the "Bailout" mechanism in React?
trick
- If a parent re-renders, but it passes the EXACT same props to a child, does the child re-render?