Sub topic 16
State identity, position, and resetting with key
This chapter assumes you know useState, props, and how a parent re-render re-renders its children. It explains how React decides which state belongs to which component, and how to reset that state on purpose.
State belongs to a position in the tree
React does not store state inside your component function. It stores state in the render tree, attached to a component's position. When a parent re-renders, React compares the new tree with the previous one. If the same component type appears at the same position, React keeps its state. If the type or position changes, React destroys the old component and its state, then mounts a new one.
This explains a common surprise. Props can change and the state stays put:
- A
Profilerenders for user 1, and you type a note into its input. - The parent re-renders
ProfilewithuserIdset to 2. - It is the same component at the same position, so React keeps the draft. The note for user 1 now sits under user 2.
Reset state with key
A key is not only for lists. It gives a component an identity. When the key changes, React treats the result as a different component. It unmounts the old one and mounts a new one with fresh state.
import { useState } from 'react';
function Profile({ userId }) {
const [draft, setDraft] = useState('');
return (
<input
value={draft}
onChange={e => setDraft(e.target.value)}
placeholder={`Note for user ${userId}`}
/>
);
}
function App() {
const [userId, setUserId] = useState(1);
return (
<>
<button onClick={() => setUserId(userId + 1)}>Next user</button>
<Profile key={userId} userId={userId} />
</>
);
}Each click on the button changes userId. That changes the key, so React discards the old Profile and its draft and mounts a new one. The input starts empty for every user.
Common errors
- Defining a component inside another component. Each render creates a new function, so React sees a new type at that position and resets the state on every render. Declare components at the top level of the module.
- Using the array index as a key in a list that reorders. State follows the key, so after a reorder it can end up attached to the wrong item. Use a stable id.
- Resetting state with an effect. Copying a prop into state and then clearing it in an effect adds an extra render and extra code. A key does the same job directly.
Conditional rendering and position
Swapping one element for another of the same type at the same position keeps the state. Swapping in a different type resets it. If you want two same-type components at one position to stay separate, give them different keys.
Exercise
A Chat component keeps an unsent message in useState. The parent renders <Chat contactId={id} />, and when the user switches contacts, the old draft still shows. What is the smallest fix, and why does it work?
Show answer
Render <Chat key={id} contactId={id} />. A different key gives the component a new identity, so React unmounts the old Chat, discards its state, and mounts a new one with an empty draft.