Sub topic 15
Resetting state with a key
This chapter assumes you know basic JavaScript (arrays, objects, arrow functions), React function components and props, and the useState hook. You have already seen keys on list items. Here you will use a key for a different job: telling React that a component is a new one, so its state starts over.
How React decides to keep state
React stores a component's state according to its position in the tree. If the same component type appears in the same position on the next render, React keeps its state and only updates the props.
That is usually what you want. It becomes a problem when the same component is reused for a different thing, such as a profile page that switches from one user to another.
Suppose Profile holds a draft message in state:
import { useState } from 'react';
function Profile({ userId }) {
const [draft, setDraft] = useState('');
return (
<section>
<h2>User {userId}</h2>
<textarea value={draft} onChange={e => setDraft(e.target.value)} />
</section>
);
}If a parent renders <Profile userId={1} /> and later <Profile userId={2} />, React sees the same type in the same spot. The draft text typed for user 1 stays in the box for user 2.
Using a key to reset
A key is not limited to lists. When you give a component a key, React uses it as part of the component's identity. If the key changes, React discards the old instance, including all of its state, and creates a new one.
function ProfilePage({ userId }) {
return <Profile key={userId} userId={userId} />;
}When userId changes from 1 to 2, the key changes too. React unmounts the old Profile and mounts a fresh one. The draft state is back to ''.
When to use it
Use a key reset when the component's identity really changes. Typical cases:
- A detail view that shows a different record, such as a user, order, or document.
- A form that should clear after switching to another item.
- A chat box where each conversation has its own draft.
The key should be a stable value that identifies the thing being shown, like an id. Do not use Math.random() or a new value on every render. That would reset the state on every render and throw away what the user typed.
Common errors
- Expecting props to reset state. Passing a new prop does not re-run
useState(initialValue). The initial value is only used on the first render. If the state should follow the prop, change the key. - Putting the key on the wrong element. The key must be on the component whose state you want to reset. A key on a child inside
Profileresets only that child. - Resetting too much. A key resets everything inside the component, including its children's state. If you only need to clear one field, update that state directly.
- Unstable keys. A key built from an index or a random value gives you resets at the wrong times.
Exercise
A Chat component keeps the typed message in useState(''). A parent renders <Chat conversationId={id} />, and the typed text carries over when id changes. What one-line change to the parent fixes it, and why does it work?
Show answer
Render <Chat key={id} conversationId={id} />. When id changes, the key changes, so React unmounts the old Chat and mounts a new one. The new instance runs useState('') again, so the message starts empty.
Exercise
Why would <Profile key={Math.random()} userId={userId} /> be a bad choice?
Show answer
It produces a new key on every render, so React treats Profile as a new component each time and resets its state on every render. Anything the user typed would be lost as soon as the parent re-rendered.