Lesson

State is a snapshot

useState gives a well a visit count that can change, and a function that asks React to change it. The number on screen is a snapshot from the last render, not a live box.

const [visits, setVisits] = useState(0);

visits is the number from this render. setVisits(visits + 1) queues a new render. On that next render, visits is the new number.

function Well() {
  const [visits, setVisits] = useState(0);
  return (
    <button onClick={() => setVisits(visits + 1)}>
      {visits}
    </button>
  );
}

onClick gets a function. onClick={fn} is right. onClick={fn()} runs it while rendering. The playground cannot run JSX. Click until visits is 3. A house goes up.

I'm ready. Try the studio →