Counting with useState
A button that counts clicks looks easy, until you try it. The number has to survive between renders. A plain variable does not: React runs your component function again on every render, so the variable drops back to its first value.
To keep a value across renders, hold it in state with useState. It returns
the current value and a setter function:
const [count, setCount] = useState(0);
The value in the brackets is the starting point, so on the first render count
is 0.
Calling the setter does two things: it stores the new value, and it re-renders the component. The next render reads the stored value, so the number you show is the number you set.
Wire the setter to a click, and the count follows every press. The button shows
Count: {count}, so each press displays the value the setter stored.
The Test for this Lesson renders your component, clicks the button once, and
checks the label. Your component is exported from App.jsx.
Challenge
A button shows Count: 0 and never moves, however many times you press it. Build
a Counter as an App component exported from App.jsx: it renders a button
labelled Count: 0 and adds one to the count each time the button is clicked.
The Test renders your component, clicks the button once, and expects the label to
read Count: 1. The starter renders a fixed Count: 0 and never changes it, so
the Test fails.