Deletions and Index Key Shift
What you'll learn: How deleting items from a list with index keys causes all subsequent items to shift and lose their identity.
When you delete an item from the middle of a list that uses index-as-key, every item after the deleted one shifts down by one position. This means every subsequent item gets a new index — and therefore a new key.
The Domino Effect of Deletion
Imagine a classroom where students are identified by their seat number. When student #3 leaves, everyone in seats 4, 5, 6, etc. shifts down to fill the gap. Now the student who was in seat #4 is in seat #3, and React thinks seat #3 is a different student.
Here's what happens:
// Before deletion: keys are [0, 1, 2, 3, 4]
const items = ['Apple', 'Banana', 'Cherry', 'Date', 'Elderberry'];
// Delete 'Cherry' (index 2)
// After deletion: keys are [0, 1, 2, 3]
// But 'Date' is now at index 2, 'Elderberry' at index 3
React sees:
- Key
2used to be 'Cherry', now it's 'Date' → destroy old, create new - Key
3used to be 'Date', now it's 'Elderberry' → destroy old, create new - Key
4used to exist, now it's gone → destroy
Result: React unnecessarily destroys and recreates components that simply moved positions. Any internal state, focus, or animations in those components are lost.
The Real Problem
This isn't just inefficient — it's visually broken. If your list items have input fields, the wrong inputs will contain the wrong text after deletion. If they have animations, they'll restart incorrectly.
Key Takeaway: Deleting items when using index keys triggers a cascade of identity changes for all subsequent items, causing React to unnecessarily recreate components and lose their state.