The stateuseState & re-renders

What actually happens when you press +1?

A component is a function. Render means React calls it and paints what it returns, so a value that has to survive from one call to the next needs somewhere to live in between. useState is that place. The setter does two jobs: it stores the new value where React keeps it, and it schedules the next call, the render that paints it.

Press +1 and the number moves, the way counters always have. Flip slow motion and press again to see the render that moved it: React runs StateCard() again, top to bottom, useState hands back the value it kept, and the line that paints the count paints the new one. Then the number has moved.

live
useStatestate-card.tsx

0

function StateCard() {
  const [count, setCount] = useState(0);

  return (
    <>
      <button onClick={() => setCount(count + 1)}>
        +1
      </button>
      <p>{count}</p>
    </>
  );
}
  • setCount stores the value where React keeps it
  • then React calls the component again

a state variable is a value React keeps between calls · setting it is permission to call the component again

state-card.tsx
// state-card.tsx
"use client";

import { useState } from "react";

export function StateCard() {
  const [count, setCount] = useState(0);
  // setCount does both jobs: it stores the value where React keeps it
  // between calls, and it schedules the render that repaints the screen.
  return (
    <Card pill="useState">
      <button onClick={() => setCount(count + 1)}>+1</button>
      <p>{count}</p>
    </Card>
  );
}