Command Palette

Search for a command to run...

Hectal
Back to the lesson: Topic 6.4 — Preserving and Resetting State
React · Example 1 of 5

Same type and position keeps state; removing it loses state

The script adds 3 to both counters. Turning on fancy styling keeps the first score (same type, same position). Hiding the second counter unmounts it, so when it comes back it starts at 0.

React keeps a component's state as long as the same component type is rendered at the same position in the tree; a different type or a removed component throws the state away, and changing a component's key resets it on purpose.

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

A profile page renders <EditProfileForm user={user} />. When the user picks another person from a list, the form still shows the previous person's edits. Fix it with one change.

02

Write a Tabs parent that shows either <Notes /> or <Todos /> (each with its own useState text box) and keeps both boxes' text when switching tabs, without lifting state up.

Explain it without notes

01

Where does React store a component's state, and what decides whether it's kept between renders?

02

Why does isA ? <Counter person="A" /> : <Counter person="B" /> keep the same state, and how do you fix it?

03

What happens to state when a component's parent changes from a div to a section?

04

Why must you never declare a component inside another component?

05

How can you keep a component's data when the component is removed?

Same type and position keeps state; removing it loses state

Preview

Press Run to see the page.

Console

Nothing logged yet.

Expected console output

After three clicks each: 3, 3
Fancy on, second hidden: 3
Second shown again: 3, 0