Sub topic 15
Resetting State with a Key
This chapter assumes you know function components, props, JSX, and useState. It also assumes you have read the earlier chapters on list keys. There, a key told React which array item was which. Here you use the same mechanism outside of lists, to tell React that a component is a different instance.
Why state sticks around
React stores a component's state according to its position in the rendered tree and its type. If the same component type renders 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 props describe a different thing and the old state no longer applies. A common case is a profile page with an editable draft:
import { useState } from 'react';
function Profile({ userId }) {
const [draft, setDraft] = useState('');
return (
<label>
Note about user {userId}
<input value={draft} onChange={e => setDraft(e.target.value)} />
</label>
);
}
function ProfilePage({ userId }) {
return <Profile userId={userId} />;
}Suppose you type "Call back on Monday" for user 1, then the page re-renders with userId set to 2. Profile is the same type in the same position. React keeps draft, so the note you wrote about user 1 now appears under user 2. The prop changed, but the state did not.
Using a key to reset
A key is not limited to list items. You can put key on any element. When the key changes between renders, React treats the element as a new one. It discards the old instance and its state, then creates a fresh instance whose state starts from the initial values.
function ProfilePage({ userId }) {
return <Profile key={userId} userId={userId} />;
}Now each user gets a separate Profile instance. When userId changes from 1 to 2, React unmounts the old Profile, which runs its effect cleanups. It then mounts a new one with draft set back to ''.
Same rule as list keys
This is the same identity rule that applies to lists. In a list, key={person.id} tells React which item is which, so that state follows the item when the array is reordered. Here, key={userId} says that the component's identity is the user. A different user means a different component.
The key only has to be unique among siblings, and it is not passed to the component as a prop. Reading props.key gives you undefined (and React warns about it). If the child needs the value, pass it again under another name, as userId is passed above.
Where to put the key
Put the key on the component whose state you want to discard. State in a component below it is discarded too, because the whole subtree is remounted. State in a component above it is not affected.
import { useState } from 'react';
function Editor({ documentId }) {
const [text, setText] = useState('');
const [showPreview, setShowPreview] = useState(false);
return (
<section>
<h2>Document {documentId}</h2>
<textarea value={text} onChange={e => setText(e.target.value)} />
<label>
<input
type="checkbox"
checked={showPreview}
onChange={e => setShowPreview(e.target.checked)}
/>
Preview
</label>
{showPreview && <pre>{text}</pre>}
</section>
);
}
function App({ documentId }) {
const [theme, setTheme] = useState('light');
return (
<div className={theme}>
<button onClick={() => setTheme(theme === 'light' ? 'dark' : 'light')}>
Toggle theme
</button>
<Editor key={documentId} documentId={documentId} />
</div>
);
}Switching documentId clears both text and showPreview, because both live inside Editor. The theme state lives in App, which has no changing key, so it survives.
Resetting from an event
The key does not have to come from a prop. You can hold a counter in state and increment it to force a reset, for example for a "Start over" button:
import { useState } from 'react';
function Quiz() {
const [answer, setAnswer] = useState('');
return (
<div>
<input value={answer} onChange={e => setAnswer(e.target.value)} />
<p>{answer.length} characters</p>
</div>
);
}
function QuizPage() {
const [attempt, setAttempt] = useState(0);
return (
<>
<Quiz key={attempt} />
<button onClick={() => setAttempt(attempt + 1)}>Start over</button>
</>
);
}Each click gives Quiz a new key, so React mounts a new Quiz with an empty answer.
Alternatives, and when a key is the better choice
You can also reset state by hand, with an effect that watches the prop:
import { useEffect, useState } from 'react';
function Profile({ userId }) {
const [draft, setDraft] = useState('');
useEffect(() => {
setDraft('');
}, [userId]);
return <input value={draft} onChange={e => setDraft(e.target.value)} />;
}This works, but it has costs:
- The component renders once with the stale
draft, then renders again after the effect runs. The user may see a flash of the old value. - You must remember to reset every piece of state. If you add a field later and forget it, stale data leaks through.
- Child components keep their own state, so you have to reset those too.
A key avoids all three. React resets everything in the subtree in one step, before the new content is shown.
| Approach | Resets nested child state | Extra render with stale state | Risk of forgetting a field |
|---|---|---|---|
| `key` on the component | Yes | No | None |
| `useEffect` that calls setters | No | Yes | Yes |
| Derive state from props during render | No | No | Yes |
Costs and edge cases
- A reset is a full remount. The DOM nodes are destroyed and recreated, and effects run their cleanup and setup again. Do not change a key on every render. That throws away state, loses input focus, and can be slow for large subtrees.
- Do not use
Math.random()orDate.now()as a key. A new key on every render means a new instance on every render. Typing in an input would lose focus after each keystroke. - Reset only what should reset. If part of the state should survive, such as a scroll position or a filter the user chose, keep that state in a parent above the keyed component, or split the component so the keyed part is small.
- Some state lives outside React. A key resets React state and recreates DOM elements. It does not clear a value held in a module variable, in
localStorage, or in a cache. - Keys must be comparable. Strings and numbers work well. Use a stable identifier such as a database id, not an object that is recreated each render.
Choosing a key for a reset
Ask what identifies the thing the component shows. If the component shows one user, the user id is the identity. If it shows one document, use the document id. If there is no natural identity and you only want a manual restart, use a counter as in the quiz example.
Exercises
Exercise
A Chat component keeps the unsent message in useState. The parent renders <Chat friendId={friendId} />. After you switch friends, the unsent message from the previous chat is still in the text box. What one-line change in the parent fixes it, and why does it work?
Show answer
Render <Chat key={friendId} friendId={friendId} />. When friendId changes, the key changes, so React unmounts the old Chat and mounts a new one. The new instance starts with the initial state, an empty message. Without the key, React sees the same component type in the same position and keeps the state.
Exercise
In the App and Editor example, theme lives in App and text lives in Editor, which has key={documentId}. After the document changes, which of these values are reset and which are kept?
Show answer
text and showPreview are reset, because they are state of Editor, which is remounted. theme is kept, because it is state of App, which sits above the keyed component and is not remounted.
Exercise
A developer sets <Search key={Math.random()} /> to "make sure the search is fresh". What goes wrong?
Show answer
Every render produces a new key, so React unmounts and remounts Search on each render. The input loses its state and focus after each keystroke that causes a parent re-render, and effects re-run needlessly. A key should change only when the identity of the content changes.