Resetting All State vs Selective Updates
You'll learn: When to use React's key prop to remount everything versus updating specific state values, and how to choose between these approaches.
The Two Strategies
You've seen that changing a component's key prop forces a complete remount—all state resets to initial values. But sometimes you only need to update part of your state when props change. Choosing the wrong strategy leads to either lost user input or stale data.
When to Reset Everything (key prop)
Use the key prop approach when:
- The component represents a fundamentally different entity (different user profile, different document)
- All state should reflect the new props (no mixing old and new data)
- You want form inputs to reset to defaults
// User profile - full reset makes sense
<UserProfile key={userId} userId={userId} />
When userId changes, the entire component unmounts and remounts fresh. Any unsaved form edits, scroll position, or internal state disappears.
When to Update Selectively (direct state updates)
Compute derived values during render or update specific state when:
- You want to preserve some local state across prop changes
- Only certain values need to sync with props
- User input should survive prop updates
function SearchResults({ category }) {
const [searchTerm, setSearchTerm] = useState('');
// searchTerm persists when category changes
// Only filter results, don't reset the search box
const filtered = results.filter(/* use both category and searchTerm */);
}
The Tradeoff
Remounting (key change) is simpler but destroys everything. Selective updates are more complex but preserve user work. Ask yourself: "If the prop changes, should the user's input disappear?" If no, don't use key.
Key Takeaway: Use the key prop when the entire component represents a new entity; use selective state updates or derived values when you need to preserve user interaction state across prop changes.