useState: What Happens on a Click

Follow a counter button through its first render, a click, and the re-render that puts the new number on screen.

React · beginner · 8 min · 8 steps · free

What you'll learn

Counter.jsx

import { useState } from 'react';

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

  function handleClick() {
    setCount(count + 1);
  }

  return (
    <button onClick={handleClick}>
      Clicked {count} times
    </button>
  );
}

Step by step

  1. React renders the component for the first time. Rendering simply means React calls the Counter function.
  2. useState(0) asks React to remember a value for this component. On the first render React stores 0 and hands it back, so count is 0.
  3. The function returns its JSX with count filled in. React turns that into a real button on the page: look at the Screen panel.
  4. The user clicks the button. React runs handleClick, the function this render attached with onClick.
  5. setCount(count + 1) works out 0 + 1 and asks React to use 1 on the next render. It does not change count here: inside this render, count is still 0.
  6. Because state was updated, React renders again: it calls Counter a second time from the top.
  7. This time useState(0) ignores the 0. That starting value is only used on the first render, so React hands back the stored value, 1.
  8. The function returns JSX with the new count. React compares it with what is on the page and updates only the text that changed, so the screen now says 1.

Common mistakes

Best practices

Key takeaways

Check yourself

What makes React render a component again?

Answer: Calling its state setter, like setCount. Only a state change (or a parent re-render) makes React call the component again.

Right after setCount(count + 1), in the same function, what is count?

Answer: The old value. The new value only appears in the next render.

·

More in State and Events