State
Values a component remembers, and what changing one actually does.
Props come from outside. State is what a component remembers for itself.
const [count, setCount] = useState(0);
useState hands back the current value and a function to change it. Calling
that function does not just assign — it tells React the component should be
drawn again, with the new value.
<button onClick={() => setCount(count + 1)}>
Clicked {count} times
</button>
Why not just count = count + 1
Because nothing would redraw. The number in the page came from a render that
already happened; assigning to a variable changes nothing on screen. setCount
is how React learns there is something new to show.
Updating from the value before
When the next value depends on the last one, pass a function:
setCount((current) => current + 1);
Two clicks in the same instant then count as two, not one — the second is computed from what the first produced rather than from a value read earlier.
Try it
- Add a Reset button.
- Add a second counter and confirm the two are independent.
- Replace
setCount(count + 1)with the function form and add a secondsetCountright after it — the difference between one and two is the point.