The scoreboard trap, and the key fix
Without a key, Ravi steals Asha's 3 points: it's the same Counter at the same position with a new prop. With key, React sees a different component and Ravi starts at 0. (Switching back to Asha also starts at 0: her instance was destroyed. The last example shows how to keep it.)
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.
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.
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
Where does React store a component's state, and what decides whether it's kept between renders?
Why does isA ? <Counter person="A" /> : <Counter person="B" /> keep the same state, and how do you fix it?
What happens to state when a component's parent changes from a div to a section?
Why must you never declare a component inside another component?
How can you keep a component's data when the component is removed?
Preview
Console
Nothing logged yet.Expected console output
Without key -> Ravi: 3
With key -> Ravi: 0