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
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>
);
}<Shop> for the first time: it calls the Shop function.useState runs for the first time, so React stores the starting value for count and returns it: 0.Shop returns JSX: a description of what the screen should show, <main>…</main>. React has not changed the page yet.Header returns JSX: a description of what the screen should show, <h1>My shop</h1>. React has not changed the page yet.<Basket> for the first time: it calls the Basket function. Its props: count = 0.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.setCount(count + 1) does not change count right away: React queues the update and will render again. In this call count is still 0.<Shop> again (render 2): it calls Shop once more, from the top.useState returns the value React has kept for count: 1. The starting value is only used on the first render.Shop returns JSX: a description of what the screen should show, <main>…</main>. React has not changed the page yet.Header renders again even though nothing about it changed: when a parent renders, React renders its children too, by default.Header returns JSX: a description of what the screen should show, <h1>My shop</h1>. React has not changed the page yet.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.Answer: Yes, by default. memo can change that.
Answer: No, its output did not change
Batching: Many Updates, One Render →