Question presented to candidate: "A profile form keeps the previous user's unsaved edits when you switch records. How would you fix it without an effect?"
What a strong answer should cover:
keyis component identity. Same key means React reuses the instance and its state; a different key means a different component, so React unmounts the old one and mounts a fresh one.- So
<ProfileForm key={userId} />resets everything inside whenuserIdchanges — no effect, no manual clearing, no risk of missing a field. - The alternative — an effect that watches the prop and calls setters — is worse: it renders once with stale state before the effect runs, it has to enumerate every piece of state, and it grows a bug every time someone adds a field.
- This is the same mechanism as index keys corrupting a list, used deliberately: React matches children by key, and a changed key is a different child.
- Scope it correctly: the key resets everything below it, including uncontrolled DOM state, refs and child component state. That is usually what you want and occasionally too much.
- The key should be stable per identity — a record id, not
Math.random(), which would remount on every render. - Reach for it when all state below should be discarded. Prefer a derived value or lifting state up when only part of it should change.
Clarifying questions expected:
- "Should absolutely everything below reset, or just one field?" — the key is all-or-nothing.
- "Is there an id that identifies the record?"
Code / implementation expected: Optional. It is a one-line change; the value is explaining why the effect version is worse.