Command Palette

Search for a command to run...

Hectal
Back to the lesson: Topic 4.2 — State: A Component's Memory
React · Example 1 of 3

A local variable forgets; state remembers

The handler does change clicks to 1, but the next render starts it at 0 again, and the screen shows 0. Only count, the state, survives each render.

useState gives a component a value that React remembers between renders plus a setter function; calling the setter stores a new value and makes React render the component again so the screen shows it.

Change the code and press Run (Ctrl+Enter). Predict what will happen first, then break it on purpose and read what changes. Your edits are saved and match the lesson page.

Ready for more? This phase has 5 hands-on exercises with automatic checks.

Practice questions

Write the code in the editor, run it, then open the model answer to compare.

01

Build a Toggle component with a button that switches between ON and OFF on each click.

02

Build a NameTag with two buttons, Asha and Ravi, and a heading Hello, <name>! that starts as Hello, guest!.

Explain it without notes

01

Why can't a component remember a value in a local variable?

02

What does useState return, and what does calling the setter do?

03

If you render a component three times, how many copies of its state exist?

04

When is the argument to useState used?

A local variable forgets; state remembers

Preview

Press Run to see the page.

Console

Nothing logged yet.

Expected console output

render: clicks = 0 | count = 0
handler: clicks is now 1
render: clicks = 0 | count = 1
handler: clicks is now 1
render: clicks = 0 | count = 2