The 'Wrong Input Has My Text' Bug
You'll learn why using index as key causes input values to stick to the wrong list items when the order changes.
The Classic Form Bug
Remember how index keys break when you reorder lists? The problem becomes visibly obvious when your list items contain form inputs. Here's what happens:
Imagine you have a list of three text inputs, each with a name label. You type something in the second input, then you reorder the list. The text you typed stays in the second position — but now it's attached to a different person's name!
Why This Happens
React uses keys to track which component instance is which. When you use index keys:
- Item at index 0 gets key
0 - Item at index 1 gets key
1(you type "Hello" here) - Item at index 2 gets key
2
Now you move the first item to the end. From React's perspective:
- Key
0is now the second item (React updates it) - Key
1is now the third item (React updates it) - Key
2is now the first item (React updates it)
But the input's internal value is stored in the DOM node itself. React doesn't know to move that DOM node — it just updates the content around it (like the label). The typed text stays put while everything else shifts.
The Real-World Scenario
This bug appears when users can:
- Reorder a to-do list with checkboxes
- Sort a table with editable cells
- Drag-and-drop items with inputs
Key Takeaway: Using index as key with form inputs causes the input values to become disconnected from their data when the list reorders — always use stable, unique IDs as keys when rendering forms in lists.