Command Palette

Search for a command to run...

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

Several state variables in one component

index and showMore are independent: moving to the next place keeps the details open. Click Next a few more times and watch it wrap around.

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?

Several state variables in one component

Preview

Press Run to see the page.

Console

Nothing logged yet.

Expected console output

Hawa Mahal in Jaipur | Has 953 small windows called jharokhas.