javascript / intermediate
Snippet
Resetting State via the Key Prop
When the 'key' of a component changes, React treats it as a brand new component, unmounting the old one and destroying its internal state. This is an elegant way to reset a form or view when the underlying data target changes without manual cleanup.
snippet.js
1
<ProfileEditor key={selectedUserId} userId={selectedUserId} />
react
Breakdown
1
key={selectedUserId}
By binding the key to the ID, React automatically resets all internal state whenever the ID changes.
2
userId={selectedUserId}
Standard prop passing; the key handles the lifecycle while this handles the data.