Skip to content

When Components Re-render

The Course
•
20 min study

Why a component re-renders

A component re-renders when:

  1. its own state receives a different value;
  2. its parent renders it again, even if the props have the same values;
  3. a context it reads changes.

React can skip work when the state is unchanged, when it reuses the same JSX element, or when a memoization optimization applies. A render isn't a promise that the DOM will change.

Rule 2 surprises people. Re-rendering doesn't mean the page changes. React calls the function, compares the result with the last one, and only touches the DOM where something differs. For most components, that's fast enough to ignore. Today is about the cases where it isn't.

Who re-renders? React · 5 files
import { createRoot } from "react-dom/client"; import App from "./App.jsx"; import "./styles.css"; createRoot(document.getElementById("root")).render(<App />); import { useState } from "react"; import CardList from "./CardList.jsx"; import { starterCards } from "./data.js"; export default function App() { const [ticks, setTicks] = useState(0); const [selectedId, setSelectedId] = useState(null); return ( <main> <h1>Study Board</h1> <div className="toolbar"> <button onClick={() => setTicks(ticks + 1)}>Tick ({ticks})</button> <span className="muted">Selected: {selectedId ?? "none"}</span> </div> <CardList cards={starterCards} onSelect={(id) => setSelectedId(id)} /> </main> ); } export default function CardList({ cards, onSelect }) { console.log("CardList rendered"); return ( <ul className="cards"> {cards.map((card) => ( <li key={card.id} className="card"> <button className="title" onClick={() => onSelect(card.id)}>{card.title}</button> </li> ))} </ul> ); } export const columns = [ { id: "todo", title: "To do" }, { id: "doing", title: "Doing" }, { id: "done", title: "Done" }, ]; export const starterCards = [ { id: 1, title: "Read about reducers", column: "todo", minutes: 20 }, { id: 2, title: "Draw the component tree", column: "doing", minutes: 15 }, { id: 3, title: "Practice useState", column: "done", minutes: 30 }, { id: 4, title: "Try context", column: "todo", minutes: 25 }, ]; body { font: 15px/1.5 system-ui, sans-serif; margin: 0; background: #f4f6f9; color: #1c2430; } main { max-width: 56rem; margin: 1rem auto; padding: 0 1rem; } h1 { margin: 0 0 0.5rem; font-size: 1.4rem; } input, select, button, textarea { font: inherit; } input, select, textarea { padding: 0.3rem 0.5rem; border: 1px solid #c4ccd6; border-radius: 6px; } button { padding: 0.25rem 0.7rem; border: 1px solid #c4ccd6; border-radius: 6px; background: white; cursor: pointer; } .toolbar { display: flex; flex-wrap: wrap; gap: 0.5rem; align-items: center; margin-bottom: 0.75rem; } .board { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 0.75rem; } .column { background: #e9edf2; border-radius: 10px; padding: 0.6rem; min-height: 6rem; } .column h2 { margin: 0 0 0.5rem; font-size: 0.95rem; } .count { color: #5c6878; font-weight: normal; } .cards { list-style: none; margin: 0; padding: 0; display: grid; gap: 0.4rem; } .card { background: white; border: 1px solid #d6dde6; border-radius: 8px; padding: 0.45rem 0.6rem; } .card button.title { border: 0; padding: 0; background: none; text-align: left; font-weight: 600; } .card.selected { outline: 2px solid #087ea4; } .muted { color: #5c6878; font-size: 0.85rem; } .panel { margin-top: 0.75rem; background: white; border: 1px solid #d6dde6; border-radius: 10px; padding: 0.75rem 1rem; } .panel h2 { margin: 0 0 0.25rem; font-size: 1.05rem; } .error { color: #b42318; }
Runs with Vite on your computer: unzip, then npm install and npm run dev.

Click Tick a few times. CardList logs CardList rendered every time, although its cards never change: its parent re-rendered:

JSX
export default function CardList({ cards, onSelect }) {
  console.log("CardList rendered");

  return (
    <ul className="cards">
      {cards.map((card) => (
        <li key={card.id} className="card">
          <button className="title" onClick={() => onSelect(card.id)}>{card.title}</button>
        </li>
      ))}
    </ul>
  );
}

memo: skip a render when props are the same

Wrap the component in memo:

JavaScript
import { memo } from "react";

function CardList({ cards, onSelect }) {
  // ...as before
}

export default memo(CardList);

memo makes React compare the new props with the old ones, using Object.is for each. If they're all the same, it reuses the last result and skips the render.

Predict

With memo in place, click Tick. Does CardList rendered still appear?

Check your prediction

Yes, every time. cards is the same array each render, but onSelect isn't: (id) => setSelectedId(id) is a new function every time App renders. To memo, a new function is a changed prop.

Stable functions

Two fixes:

  • Pass something that's already stable. State setters never change, so onSelect={setSelectedId} is the same function every render.

  • useCallback keeps the same function between renders until its dependencies change:

    JavaScript
    const handleSelect = useCallback((id) => setSelectedId(id), []);

Use the first fix here. Now Tick logs nothing. Selecting a card still works, and doesn't re-render CardList either, because its props didn't change.

Measure, then useMemo

useMemo does for a value what memo does for a component: it keeps the last result until its dependencies change. Before reaching for it, measure. This lab's slowTotal stands in for an expensive calculation and logs how long it took:

Measure, then memoise React · 3 files
import { createRoot } from "react-dom/client"; import App from "./App.jsx"; import "./styles.css"; createRoot(document.getElementById("root")).render(<App />); import { useState } from "react"; const starterCards = [ { id: 1, title: "Read about memo", minutes: 20 }, { id: 2, title: "Try useMemo", minutes: 15 }, { id: 3, title: "Profile a slow list", minutes: 25 }, ]; // Pretends to be an expensive calculation, and times itself. function slowTotal(cards) { const start = performance.now(); while (performance.now() - start < 100) { // Busy on purpose. } const total = cards.reduce((sum, card) => sum + card.minutes, 0); console.log(`slowTotal took ${Math.round(performance.now() - start)} ms`); return total; } export default function App() { const [cards, setCards] = useState(starterCards); const [dark, setDark] = useState(false); const total = slowTotal(cards); function addCard() { setCards([...cards, { id: cards.length + 1, title: `Card ${cards.length + 1}`, minutes: 10 }]); } return ( <main style={{ background: dark ? "#1f2933" : "white", color: dark ? "white" : "black" }}> <h1>Study Board</h1> <div className="toolbar"> <button onClick={() => setDark(!dark)}>{dark ? "Light mode" : "Dark mode"}</button> <button onClick={addCard}>Add card</button> </div> <p>{cards.length} cards, {total} minutes</p> </main> ); } body { font: 15px/1.5 system-ui, sans-serif; margin: 0; background: #f4f6f9; color: #1c2430; } main { max-width: 56rem; margin: 1rem auto; padding: 0 1rem; } h1 { margin: 0 0 0.5rem; font-size: 1.4rem; } input, select, button, textarea { font: inherit; } input, select, textarea { padding: 0.3rem 0.5rem; border: 1px solid #c4ccd6; border-radius: 6px; } button { padding: 0.25rem 0.7rem; border: 1px solid #c4ccd6; border-radius: 6px; background: white; cursor: pointer; } .toolbar { display: flex; flex-wrap: wrap; gap: 0.5rem; align-items: center; margin-bottom: 0.75rem; } .board { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 0.75rem; } .column { background: #e9edf2; border-radius: 10px; padding: 0.6rem; min-height: 6rem; } .column h2 { margin: 0 0 0.5rem; font-size: 0.95rem; } .count { color: #5c6878; font-weight: normal; } .cards { list-style: none; margin: 0; padding: 0; display: grid; gap: 0.4rem; } .card { background: white; border: 1px solid #d6dde6; border-radius: 8px; padding: 0.45rem 0.6rem; } .card button.title { border: 0; padding: 0; background: none; text-align: left; font-weight: 600; } .card.selected { outline: 2px solid #087ea4; } .muted { color: #5c6878; font-size: 0.85rem; } .panel { margin-top: 0.75rem; background: white; border: 1px solid #d6dde6; border-radius: 10px; padding: 0.75rem 1rem; } .panel h2 { margin: 0 0 0.25rem; font-size: 1.05rem; } .error { color: #b42318; }
Runs with Vite on your computer: unzip, then npm install and npm run dev.

Click Dark mode a few times. Every click logs slowTotal took 100 ms (give or take a millisecond), and the button feels sticky. That log is your measurement: the total is recalculated on every render, although switching the theme can't change it.

Now keep the result between renders, recalculating only when cards changes:

JavaScript
const total = useMemo(() => slowTotal(cards), [cards]);

Import useMemo from "react". Predict which buttons log a time now, then click both.

Check your prediction

Dark mode logs nothing: cards is the same array, so React hands back the last total without calling slowTotal. Add card logs once, because the new cards array is a changed dependency, and the total really does need recalculating.

A console.log timer is enough for one calculation. For a whole app, the React DevTools browser extension has a Profiler tab: record while you click, and it lists every component that rendered and how long each took. Look at the numbers before and after a memo or useMemo. If they don't drop, take it out again.

useMemo also keeps a memoized child's props stable: useMemo(() => cards.filter(...), [cards]) hands a memo child the same array until cards changes.

Don't memo everything

memo, useCallback and useMemo cost a comparison on every render, and they make code harder to read. Use them when you've measured a problem: a slow component, or one that re-renders very often for no reason. React's own compiler, when you use it, adds this memoization for you, so writing it by hand is becoming less necessary.

Exercise

Keep an inline handler

Suppose App needs to log each selection, so it can't just pass setSelectedId. Keep onSelect an inline-looking handler that logs selected 3 and sets the state, without making CardList re-render on Tick.

Your working space React · 5 files
import { createRoot } from "react-dom/client"; import App from "./App.jsx"; import "./styles.css"; createRoot(document.getElementById("root")).render(<App />); import { useState } from "react"; import CardList from "./CardList.jsx"; import { starterCards } from "./data.js"; export default function App() { const [ticks, setTicks] = useState(0); const [selectedId, setSelectedId] = useState(null); return ( <main> <h1>Study Board</h1> <div className="toolbar"> <button onClick={() => setTicks(ticks + 1)}>Tick ({ticks})</button> <span className="muted">Selected: {selectedId ?? "none"}</span> </div> <CardList cards={starterCards} onSelect={(id) => setSelectedId(id)} /> </main> ); } export default function CardList({ cards, onSelect }) { console.log("CardList rendered"); return ( <ul className="cards"> {cards.map((card) => ( <li key={card.id} className="card"> <button className="title" onClick={() => onSelect(card.id)}>{card.title}</button> </li> ))} </ul> ); } export const columns = [ { id: "todo", title: "To do" }, { id: "doing", title: "Doing" }, { id: "done", title: "Done" }, ]; export const starterCards = [ { id: 1, title: "Read about reducers", column: "todo", minutes: 20 }, { id: 2, title: "Draw the component tree", column: "doing", minutes: 15 }, { id: 3, title: "Practice useState", column: "done", minutes: 30 }, { id: 4, title: "Try context", column: "todo", minutes: 25 }, ]; body { font: 15px/1.5 system-ui, sans-serif; margin: 0; background: #f4f6f9; color: #1c2430; } main { max-width: 56rem; margin: 1rem auto; padding: 0 1rem; } h1 { margin: 0 0 0.5rem; font-size: 1.4rem; } input, select, button, textarea { font: inherit; } input, select, textarea { padding: 0.3rem 0.5rem; border: 1px solid #c4ccd6; border-radius: 6px; } button { padding: 0.25rem 0.7rem; border: 1px solid #c4ccd6; border-radius: 6px; background: white; cursor: pointer; } .toolbar { display: flex; flex-wrap: wrap; gap: 0.5rem; align-items: center; margin-bottom: 0.75rem; } .board { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 0.75rem; } .column { background: #e9edf2; border-radius: 10px; padding: 0.6rem; min-height: 6rem; } .column h2 { margin: 0 0 0.5rem; font-size: 0.95rem; } .count { color: #5c6878; font-weight: normal; } .cards { list-style: none; margin: 0; padding: 0; display: grid; gap: 0.4rem; } .card { background: white; border: 1px solid #d6dde6; border-radius: 8px; padding: 0.45rem 0.6rem; } .card button.title { border: 0; padding: 0; background: none; text-align: left; font-weight: 600; } .card.selected { outline: 2px solid #087ea4; } .muted { color: #5c6878; font-size: 0.85rem; } .panel { margin-top: 0.75rem; background: white; border: 1px solid #d6dde6; border-radius: 10px; padding: 0.75rem 1rem; } .panel h2 { margin: 0 0 0.25rem; font-size: 1.05rem; } .error { color: #b42318; }
Runs with Vite on your computer: unzip, then npm install and npm run dev.
Hint 1: the idea

Memoization only skips a parent-driven render when the child receives the same props. Stabilize the function prop without hiding values it reads.

Hint 2: a first step

useCallback with an empty dependency list. The setter inside it is stable, so nothing needs to be listed.

Show one solution
JavaScript
const handleSelect = useCallback((id) => {
  console.log("selected", id);
  setSelectedId(id);
}, []);
JSX
<CardList cards={starterCards} onSelect={handleSelect} />

Import useCallback from "react", and keep memo on CardList.

Was this article helpful?

Your response is saved on this device.