Using array indices as keys in React can cause unexpected bugs and poor performance, especially when list items change order, are added, or removed.
React uses keys to track and reconcile items between renders — if keys are unstable, React can mix up elements.
Example of the Problem
const users = ["Alice", "Bob", "Charlie"];
function UserList() {
return (
<ul>
{users.map((user, index) => (
<li key={index}>{user}</li>
))}
</ul>
);
}
If you insert or remove an item from the array:
// Insert "David" at the start
users.unshift("David");
React now reuses old DOM nodes based on indices — causing:
- Wrong component state mapping
- Inputs retaining wrong values
- Flickering or broken animations
Real Bug Example
{todos.map((todo, index) => (
<input key={index} value={todo.text} />
))}
If one todo is deleted, React reuses the same input for the next item, so user text appears to “jump” between fields.
✅ Better Approach
Use a unique, stable identifier (like id):
{todos.map((todo) => (
<input key={todo.id} value={todo.text} />
))}
💡 In Short:
Using array indices as keys causes incorrect UI updates when items change.
Always use a unique, stable key (like an ID) to ensure React correctly tracks each element.