When Does a Component Render?

Click once and count the renders: the parent, and every child with it. See why that is cheap, and what actually reaches the page.

React · intermediate · 7 min · 18 steps · free

What you'll learn

RenderTree.jsx

import { useState } from 'react';

function Header() {
  return <h1>My shop</h1>;
}

function Basket({ count }) {
  return <p>{count} items in the basket</p>;
}

export default function Shop() {
  const [count, setCount] = useState(0);

  return (
    <main>
      <Header />
      <Basket count={count} />
      <button onClick={() => setCount(count + 1)}>Add item</button>
    </main>
  );
}

Step by step

  1. React renders <Shop> for the first time: it calls the Shop function.
  2. useState runs for the first time, so React stores the starting value for count and returns it: 0.
  3. Shop returns JSX: a description of what the screen should show, <main>…</main>. React has not changed the page yet.
  4. Header has no props and no state. It renders because its parent did.
  5. Header returns JSX: a description of what the screen should show, <h1>My shop</h1>. React has not changed the page yet.
  6. React renders <Basket> for the first time: it calls the Basket function. Its props: count = 0.
  7. Basket returns JSX: a description of what the screen should show, <p>0 items in the basket</p>. React has not changed the page yet.
  8. React turns the JSX into real page elements and shows them: look at the Screen panel.
  9. You click Add item. Only Shop's state will change.
  10. setCount(count + 1) does not change count right away: React queues the update and will render again. In this call count is still 0.
  11. React renders <Shop> again (render 2): it calls Shop once more, from the top.
  12. useState returns the value React has kept for count: 1. The starting value is only used on the first render.
  13. Shop returns JSX: a description of what the screen should show, <main>…</main>. React has not changed the page yet.
  14. Header renders again even though nothing about it changed: when a parent renders, React renders its children too, by default.
  15. Header returns JSX: a description of what the screen should show, <h1>My shop</h1>. React has not changed the page yet.
  16. Basket gets the new count, 1.
  17. Basket returns JSX: a description of what the screen should show, <p>1 items in the basket</p>. React has not changed the page yet.
  18. Only the basket text changes on the page; the <h1> is left alone. The React group shows every component rendered twice.

Common mistakes

Best practices

Key takeaways

Check yourself

Parent state changes. Do children render?

Answer: Yes, by default. memo can change that.

Header rendered again. Was its <h1> rebuilt?

Answer: No, its output did not change

More in How Rendering Works