Keys identify siblings across renders. Stable identity lets state follow the same logical item when ordering changes.
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: Use a database ID for editable rows that can be sorted or inserted. 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: Give rows stable IDs
Identify the logical item independently of its current position. Sorting changes position while item identity stays the same.
Step 2: Observe local state
Edit a row’s input, then reorder the list. The edited state should follow that item rather than its old index.
Step 3: Use keys at the mapping boundary
Pass key={item.id} on the mapped component. Keys need uniqueness among siblings, not globally across the application.
Worked scenario
Use a database ID for editable rows that can be sorted or inserted.
return items.map(item => <EditableRow
key={item.id}
item={item}
/>);If row A moves from index zero to index two, its ID stays A. An index key would associate the old position’s component state with whichever item now occupies that position.
Common mistake
Index keys can attach one row’s input state to another row after reordering.
Verify the behavior
Edit a row, insert above it, sort and delete another row. Check that edits follow the original item; random keys should demonstrate unintended resets.
Interview exercise
Why do random keys lose edits?
Answer and reasoning
New keys make React treat each row as a new component, recreating its state and DOM ownership.
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.