State follows a component’s identity at its tree position. Changing its key deliberately creates a fresh instance when a different entity should own fresh local state.
Before you start
You should know how a function component renders JSX, receives props and handles events. Follow the value through render, interaction and the next render. Small snippets below belong inside an existing React application unless they are explicitly shown as complete components.
The practical goal is to reason through this situation: Key an editor by document ID to reset its draft when switching documents. Read the walkthrough first, then try the interview exercise before opening its answer. The important part is explaining the decision and its consequences, rather than remembering a definition alone.
Step-by-step walkthrough
Step 1: Choose the state owner
A draft belongs to the selected document. Decide whether switching documents should reset or preserve unfinished edits.
Step 2: Reset through identity
Key the editor by document ID when each selection needs fresh local state. A stable ID changes only on document changes.
Step 3: Lift retained drafts
If users expect drafts to survive switching, store them by document ID above the keyed editor and pass the correct draft down.
Worked scenario
Key an editor by document ID to reset its draft when switching documents.
<DocumentEditor key={document.id} document={document} />Selecting document B replaces A’s editor instance, so B starts from its own initialization. Selecting B again does not reset it. A random key would reset on unrelated parent renders and lose edits.
Common mistake
A changing key on every render destroys state continuously.
Verify the behavior
Switch A-to-B-to-A and state the intended draft behavior first. Trigger an unrelated parent update while editing B; that should not erase B’s work.
Interview exercise
Preserve drafts across document switches.
Answer and reasoning
Store drafts by document ID in an owner above the keyed editor if retaining previous drafts is required.
Continue learning
Compare the scenario with the React interview questions and test your understanding with the React MCQs. For terminology and implementation details, consult the reference material.