Keys in Conditional Rendering
You'll learn how to control component identity when the same type of component appears in different branches of a conditional.
The Problem: Ambiguous Component Identity
When you render the same component type in both the true and false branches of a conditional, React might reuse the component instance instead of unmounting and remounting it. This can preserve state unintentionally.
Consider this example:
function ProfileForm({ isEditMode }) {
if (isEditMode) {
return <TextInput placeholder="Edit name" />;
}
return <TextInput placeholder="View name" />;
}
Both branches render TextInput. React sees the same component type in the same position and may preserve the internal state of that TextInput even when isEditMode changes.
The Solution: Different Keys for Different Identities
If you want React to treat these as different instances (unmount the old, mount the new), give them different key props:
function ProfileForm({ isEditMode }) {
if (isEditMode) {
return <TextInput key="edit" placeholder="Edit name" />;
}
return <TextInput key="view" placeholder="View name" />;
}
Now React sees two distinct identities. Switching between branches will reset the component's state because the key changed.
When This Matters
Use this pattern when:
- You want to reset state when switching modes
- The same component type appears in multiple conditional branches
- Default behavior (state preservation) causes bugs
Think of it like name tags at a conference: two people might wear the same outfit, but different name tags tell you they're different people.
Key Takeaway: Use different keys on the same component type in conditional branches to force React to unmount and remount, resetting internal state.