Sub topic 5
Reset state with a key, not an Effect
This chapter assumes you know function components, useState, props, and the basics of useEffect with a dependency array. You should also know that React re-renders a component when its state or props change.
The problem: state that survives a prop change
React keeps a component's state as long as the component stays at the same position in the tree. If a parent re-renders the same component type in the same place with different props, React reuses the existing instance and its state.
Here is a profile page with a comment box. The userId prop changes when the user navigates to another profile. The comment typed for the first user stays in the box:
import { useState } from 'react';
export default 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}
/>
);
}A comment written for one person now appears under another person's profile. That is a bug.
The Effect approach and why it falls short
A common fix is to clear the state in an Effect when the prop changes:
import { useState, useEffect } from 'react';
function Profile({ userId }) {
const [comment, setComment] = useState('');
useEffect(() => {
setComment('');
}, [userId]);
return (
<textarea
value={comment}
onChange={e => setComment(e.target.value)}
/>
);
}This works, but it has two problems:
- Stale render. React first renders with the old comment and the new
userId. The Effect runs after that render and callssetComment(''), which triggers a second render. Users can briefly see the wrong value, and the work is done twice. - Incomplete reset. If
Profilehas child components with their own state, you must reset each of them too. Every new piece of state is another place to forget.
The fix: give the component a key
A key tells React which component instance is which. When the key changes, React discards the old instance, including all its state and its children's state, and creates a fresh one.
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 starts with comment set to '' for each user. No Effect runs and no extra render happens. State in any nested component resets too.
Where to put the key
Put the key on the component whose state you want to reset, at the place where you render it. Keys are not passed as props, so Profile cannot read props.key. That is why userId is still passed separately.
Keys are not limited to lists. Any component can have one, and changing it is how you say "this is a different thing now."
Common errors
- Using an index or a constant as the key. If the key does not change when the identity changes, nothing resets. Use a value that identifies the thing, such as a user ID.
- Using a key that changes on every render, such as
Math.random(). React recreates the component each render, so all state is lost constantly and inputs lose focus. - Putting the key on the wrong element. A key inside
Profile, on its<textarea>, resets only that element. It does not reset state thatProfileitself holds. - Expecting to keep some state. A key resets everything below it. If only part of the state should reset, the next chapter covers adjusting state when a prop changes.
Summary of the decision
| Situation | Approach |
|---|---|
| All state should reset when an identity prop changes | Add `key` to the component |
| Only some state should change with a prop | Adjust that state, or restructure it |
| State is derived from props | Calculate it during render |
Exercise
A Chat component keeps a draft message in state. It receives a contactId prop, and the draft must clear when the user switches contacts. Without using an Effect, how do you do this? Where does the change go?
Show answer
In the parent, render the component with the identity as its key: <Chat contactId={contactId} key={contactId} />. When contactId changes, React unmounts the old Chat and mounts a new one, so the draft state starts empty again. No Effect or second render is needed.
Exercise
A developer writes <Profile userId={userId} key={Math.random()} /> to be safe. What goes wrong?
Show answer
The key changes on every render, so React remounts Profile each time the parent renders. State is reset constantly, typed text disappears, and focus is lost. The key should be a stable value that changes only when the identity changes, such as userId.