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.

Try it

Add a second button that resets the count to 0. It needs no new state.

loading editor…

loading React…

useState is available directly in these exercises. In a real project you would import it from react.

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.

Try it

Change every setCount(count + 1) to setCount(c => c + 1) and click again. Now it adds three.

loading editor…

loading React…

Three calls, one increment. All three read the same count from this render, so all three set the same value.

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.

Next: Replacing, Not Editing →
← Back