Index keys versus stable ids when deleting a row
Both lists deleted Milk. With index keys, React kept the components for keys 0 and 1 and dropped key 2, so the Eggs row now holds Milk's note: the input's own state stayed with the position, not with the item. With item.id keys the right row is removed.
Six mistakes show up in almost every React codebase: copying props into state, chains of effects that set state, index keys on lists that change, giant components, drilling every prop everywhere, and memoising by reflex; each has a small, well-known fix taught earlier in this course.
Change the code and press Run (Ctrl+Enter). Predict what will happen first, then break it on purpose and read what changes. Your edits are saved and match the lesson page.
Ready for more? This phase has 5 hands-on exercises with automatic checks.
Practice questions
Write the code in the editor, run it, then open the model answer to compare.
Refactor: function Price({ amount, rate }) { const [converted, setConverted] = useState(0); useEffect(() => { setConverted(amount * rate); }, [amount, rate]); return <span>{converted.toFixed(2)}</span>; }
This list uses key={i} and each row has a checkbox with local state. Items can be sorted. What breaks, and how do you fix it?
Explain it without notes
Why is copying a prop into state a bug, and what are the fixes?
What is wrong with a chain of effects that set state, and how do you refactor it?
Why do index keys cause bugs, and when are they acceptable?
How would you approach memoisation in a React codebase?
Preview
Console
Nothing logged yet.Expected console output
broken: Eggs / note: Milk | Rice / note: Eggs
fixed: Eggs / note: Eggs | Rice / note: Rice