Command Palette

Search for a command to run...

Hectal
Back to the lesson: Topic 22.7 — Common React Anti-Patterns and Their Fixes
React · Example 3 of 4

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.

01

Refactor: function Price({ amount, rate }) { const [converted, setConverted] = useState(0); useEffect(() => { setConverted(amount * rate); }, [amount, rate]); return <span>{converted.toFixed(2)}</span>; }

02

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

01

Why is copying a prop into state a bug, and what are the fixes?

02

What is wrong with a chain of effects that set state, and how do you refactor it?

03

Why do index keys cause bugs, and when are they acceptable?

04

How would you approach memoisation in a React codebase?

Index keys versus stable ids when deleting a row

Preview

Press Run to see the page.

Console

Nothing logged yet.

Expected console output

broken: Eggs / note: Milk | Rice / note: Eggs
fixed: Eggs / note: Eggs | Rice / note: Rice