Key Prop for Efficient Updates
RE · Performancesyntax
// Stable keys help React identify which items changed
<Item key={item.id} />
// Reset component state by changing the key
<Form key={selectedUserId} />example
// Using key to reset component state
function UserEditor({ userId }) {
// When userId changes, React destroys the old Form
// and mounts a fresh one with clean state
return <ProfileForm key={userId} userId={userId} />;
}
function ProfileForm({ userId }) {
const [name, setName] = useState('');
const [bio, setBio] = useState('');
useEffect(() => {
fetchUser(userId).then(user => {
setName(user.name);
setBio(user.bio);
});
}, [userId]);
return (
<form>
<input value={name} onChange={e => setName(e.target.value)} />
<textarea value={bio} onChange={e => setBio(e.target.value)} />
</form>
);
}Note Changing a component's key forces React to unmount and remount it, resetting all internal state. This is a clean way to 'reset' a form or component when switching between items without manually clearing each state variable.