ReactEasy
Key issues in list?
Key problems in lists come from missing, duplicate, unstable or index-based keys. They cause React to reuse the wrong DOM nodes and component state, so inputs show the wrong text, checkboxes jump between rows, animations glitch, and items remount needlessly. Use stable, unique IDs from your data.
The issues
- Missing keys: React warns and falls back to indexes.
- Index as key with lists that change order, insert at the top, filter or delete. State stays with positions instead of items.
- Random keys during render (
Math.random(),crypto.randomUUID()inline): every render remounts every item, losing state and focus and hurting performance. - Duplicate keys: React warns, and items may be skipped or duplicated in the DOM.
- Keys on the wrong element: the key must be on the outermost element returned by
map, not an inner child. - Keys that change for the same item (for example built from mutable fields like a title): editing the title remounts the row.
Fixes
- Use database IDs, slugs or other stable identifiers.
- Generate IDs once, when data is created or loaded, not during render.
- Combine fields if needed:
key={`${order.id}-${line.sku}`}. - Index keys are fine only for static lists that never change.
Keys as a tool
Changing a key on purpose resets a component, for example <Form key={selectedUserId} />.
Code example
tsx
1import { useState } from "react";23type Row = { id: string; label: string };45function EditableRow({ row }: { row: Row }) {6 const [note, setNote] = useState(""); // local state tied to the component instance7 return (8 <li>9 {row.label} <input value={note} onChange={(e) => setNote(e.target.value)} placeholder="note" />10 </li>11 );12}1314export function KeyBugs() {15 const [rows, setRows] = useState<Row[]>([{ id: "a", label: "Alpha" }, { id: "b", label: "Beta" }]);16 const addTop = () => setRows((r) => [{ id: crypto.randomUUID(), label: `New ${r.length}` }, ...r]); // id created once1718 return (19 <div>20 <button onClick={addTop}>Add to top</button>2122 {/* Bug: index keys - notes shift to the wrong row after "Add to top" */}23 <ul>{rows.map((row, i) => <EditableRow key={i} row={row} />)}</ul>2425 {/* Bug: random keys - every row remounts on each render, notes are lost */}26 {/* <ul>{rows.map((row) => <EditableRow key={Math.random()} row={row} />)}</ul> */}2728 {/* Correct: stable ids from the data */}29 <ul>{rows.map((row) => <EditableRow key={row.id} row={row} />)}</ul>30 </div>31 );32}
Practice this question
Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the React set.