Sub topic 5
Reset state with a key, not an Effect
Sometimes a component must start over when something about its context changes. A comment box should be empty when you switch to a different user's profile. A form should clear when you open a different record. A common first attempt is an Effect that calls setState when a prop changes. React has a better tool for this: the key attribute.
This chapter assumes you can write function components with JSX, use useState and props, read a useEffect dependency array, and recognize that a component re-renders when its state or props change.
The problem: state that outlives its context
React keeps a component's state attached to its position in the tree. If the same component type renders in the same place, React reuses it and keeps its state, even when the props describe something entirely different.
Here is a profile page with a comment box.
import { useState } from 'react';
const users = [
{ id: 1, name: 'Ada' },
{ id: 2, name: 'Grace' },
];
export default function App() {
const [userId, setUserId] = useState(1);
return (
<>
{users.map(user => (
<button key={user.id} onClick={() => setUserId(user.id)}>
{user.name}
</button>
))}
<ProfilePage userId={userId} />
</>
);
}
function ProfilePage({ userId }) {
return <Profile userId={userId} />;
}
function Profile({ userId }) {
const [comment, setComment] = useState('');
return (
<textarea
value={comment}
onChange={e => setComment(e.target.value)}
placeholder={'Comment on user ' + userId}
/>
);
}Type a draft for Ada, then click Grace. The draft stays in the box. React sees <Profile> in the same position with the same type, so it keeps the instance and its comment state. Only the userId prop changed. The draft now sits under the wrong person, and you could post it to the wrong profile.
The Effect approach and why it falls short
The obvious fix is to watch userId and clear the state.
function Profile({ userId }) {
const [comment, setComment] = useState('');
// Avoid: resets state after the render has already happened.
useEffect(() => {
setComment('');
}, [userId]);
return (
<textarea
value={comment}
onChange={e => setComment(e.target.value)}
placeholder={'Comment on user ' + userId}
/>
);
}This works on screen, but it has three problems.
- A wasted render with stale data. When
userIdchanges, React rendersProfilewith the newuserIdand the oldcomment. It commits that to the screen. Only then does the Effect run, callsetComment(''), and trigger a second render. The stale draft is briefly visible. - It only resets the state you remember. If
Profilehas five pieces of state, you need five reset calls. Add a sixth later and you must remember to add it. State in child components, such as a nested form or an accordion, is not reset at all unless you repeat the pattern in each one. - It hides the intent. A reader sees "sync state to a prop" and has to work out that the goal is "treat this as a different profile".
The root issue is that you are using an Effect to react to a change in props, which the previous chapters showed is usually a sign that the logic belongs elsewhere.
The fix: give the component a key
Pass the identifying value as a key from the parent.
import { useState } from 'react';
export default function ProfilePage({ userId }) {
// A different key makes React create a fresh Profile with fresh state.
return <Profile userId={userId} key={userId} />;
}
function Profile({ userId }) {
const [comment, setComment] = useState('');
return (
<textarea
value={comment}
onChange={e => setComment(e.target.value)}
placeholder={'Comment on user ' + userId}
/>
);
}Now Profile has no Effect and no reset code. When key changes, React treats the new element as a different component instance. It unmounts the old one, discarding its state, and mounts a new one, running useState('') from scratch. The first render with the new userId already shows an empty box. No stale frame is committed, and no second render pass is needed.
Keys are identity, not just a list feature
You have likely used key when mapping over arrays, where it helps React match items between renders. The underlying idea is wider: a key tells React which "thing" an element represents. Same key means the same thing, so keep its state. A different key means a different thing, so start fresh.
Because of this, you can put a key on any component, not only on list items. It does not need to be part of an array. Keys are not passed as props, so Profile cannot read props.key. If the child needs the value, pass it separately, as userId is here.
Where to put the key
The key must be on the element that creates the instance you want to reset, and it must be set by the parent that renders it. Keys only distinguish siblings in the same position, so the component must be the one whose state you want to reset, or an ancestor of it.
// Resets Profile and everything below it.
<Profile userId={userId} key={userId} />
// Does nothing useful: the key is inside Profile, so Profile itself
// is never remounted and its own state survives.
function Profile({ userId }) {
const [comment, setComment] = useState('');
return <textarea key={userId} value={comment} onChange={e => setComment(e.target.value)} />;
}In the second example, the <textarea> DOM node is recreated when userId changes, but comment lives in Profile, which stays mounted. The text would reappear in the new textarea because the state was never reset. Put the key where the state is owned, or higher up.
What a key reset affects
A key change resets the entire subtree under the keyed element.
- All
useStateanduseReducerstate in that component. - State in every descendant component.
- DOM state, such as the contents of an uncontrolled input, scroll position, text selection, and focus.
- Refs created in that subtree.
It also runs Effect cleanups for the old instance on unmount, then runs the Effects of the new instance on mount. If Profile subscribes to a chat room, the subscription is torn down and recreated. That is often what you want, but it is a real cost to keep in mind.
Resetting on demand with a counter key
The value does not have to come from props. You can reset a form from a button by keeping a counter in the parent.
import { useState } from 'react';
export default function App() {
const [version, setVersion] = useState(0);
return (
<>
<button onClick={() => setVersion(v => v + 1)}>Reset form</button>
<Survey key={version} />
</>
);
}
function Survey() {
const [name, setName] = useState('');
const [rating, setRating] = useState(5);
return (
<form>
<input value={name} onChange={e => setName(e.target.value)} placeholder="Name" />
<input
type="number"
min="1"
max="10"
value={rating}
onChange={e => setRating(Number(e.target.value))}
/>
<p>{name || 'Anonymous'} rated {rating}</p>
</form>
);
}Each click on the button changes version, so Survey remounts with name as '' and rating as 5. You do not write any reset logic inside Survey, and if you add a field later it is reset automatically.
Gotchas and limits
- Keys must be stable between renders. Never use
Math.random()orcrypto.randomUUID()inline as a key. A new value on every render remounts the component on every render. It loses state, drops input focus after each keystroke, and reruns Effects. - Use a real identity. The record ID is a good key. An array index is a poor one if the list can reorder, and an index would not tell you "this is a different user" in any case.
- Remounting is not free. For a large subtree, discarding and rebuilding all the DOM may be slower than a targeted state update. If only one small piece of state needs to change, a key may be too blunt. The next chapter covers adjusting some state when a prop changes.
- You lose everything below the key, whether or not you meant to. If the user types a draft, switches users, and switches back, the draft is gone. If you want drafts to survive, keep them in a parent as data rather than relying on component state.
A parent that stores drafts per user might look like this.
import { useState } from 'react';
export default function ProfilePage({ userId }) {
const [drafts, setDrafts] = useState({});
return (
<Profile
key={userId}
userId={userId}
draft={drafts[userId] ?? ''}
onDraftChange={text => setDrafts({ ...drafts, [userId]: text })}
/>
);
}
function Profile({ userId, draft, onDraftChange }) {
return (
<textarea
value={draft}
onChange={e => onDraftChange(e.target.value)}
placeholder={'Comment on user ' + userId}
/>
);
}Here the key is still useful for resetting other local state, such as scroll position or a collapsed panel, while the drafts live above it.
Choosing between the options
| Situation | Better tool |
|---|---|
| The whole component should start over when an identity changes | `key` on the component |
| A value can be computed from props or other state | Calculate it during render |
| Only part of the state depends on a prop | Adjust that state during render, or restructure state (next chapter) |
| State should survive switching between items | Store it in a parent, keyed by item ID |
| You must connect to something outside React when a prop changes | An Effect with cleanup |
Summary
State is tied to a component's identity in the tree. When a prop changes but the identity stays the same, state carries over, which is usually correct, but wrong when the prop means "this is something else now". An Effect that resets state afterward causes an extra render, shows stale data, and only resets what you list. A key declares the identity change up front, so React rebuilds the subtree with fresh state in a single pass.
Exercise
A Chat component keeps draftMessage in state and receives a contactId prop. You see that switching contacts leaves the old draft in the input. A teammate adds useEffect(() => setDraftMessage(''), [contactId]). Describe two drawbacks of this fix and show the replacement that avoids them.
Show answer
Drawbacks: React first renders and commits the new contact with the old draft, so the stale text is briefly on screen, and then the Effect triggers a second render. Also, it only resets the state you list, so other state in Chat or its children would still carry over. Replacement: remove the Effect and have the parent render <Chat contactId={contactId} key={contactId} />. Changing the key unmounts the old instance and mounts a new one, so all state starts fresh in one pass.
Exercise
You write function Editor({ docId }) { const [text, setText] = useState(''); return <textarea key={docId} value={text} onChange={e => setText(e.target.value)} />; } and expect text to clear when docId changes. It does not clear. Why, and how do you fix it?
Show answer
The key is on the <textarea> inside Editor, but text is owned by Editor, which stays mounted when docId changes. React recreates the DOM node, but text still holds the old value, so it is displayed again. Move the key to where Editor is rendered: <Editor docId={docId} key={docId} />. Then Editor itself is remounted and useState('') runs again.