useState
What this is. State is data a component remembers between renders. useState declares one piece of it.
It returns two things: the current value, and a function that replaces it. Calling that function is what tells React to render again.
The argument is the starting value, and only that. useState(0) means start at zero on the first render. On every render after that, the argument is ignored, because the state already exists. People often expect it to reset the value, and it never does.
✦ The mistake everyone makes once
Calling the setter does not change the variable you are holding. That variable belongs to the render you are currently in, and it will never change. This is not a bug and not a delay you can wait out. It is what makes each render a consistent snapshot rather than something shifting under you mid-function.
The updater form. When the new value depends on the old one, pass a function instead of a value. React calls it with the latest value rather than the one your render captured.
It is never wrong to prefer this form, and it is the fix for a whole category of bugs that are otherwise very hard to see.
Mark this lesson complete
Signed in, your progress follows you to every device.