Why Not Use Index as Key in React: Explained Simply
Using
index as a key in React can cause UI bugs when list items change order, get added, or removed because React relies on keys to track elements. This can lead to incorrect component updates or lost state. It's better to use unique and stable IDs as keys.Syntax
In React, keys are added as a special key attribute to elements in a list to help React identify which items changed.
Example syntax using index as key:
{items.map((item, index) => <li key={index}>{item}</li>)}
Here, index is the position of the item in the array.
jsx
const items = ['Apple', 'Banana', 'Cherry']; function FruitList() { return ( <ul> {items.map((item, index) => ( <li key={index}>{item}</li> ))} </ul> ); }
Output
<ul><li>Apple</li><li>Banana</li><li>Cherry</li></ul>
Example
This example shows a list where items can be reordered. Using index as key causes React to confuse items, leading to wrong updates or lost input focus.
jsx
import React, { useState } from 'react'; const initialItems = [ { id: 'a', text: 'First' }, { id: 'b', text: 'Second' }, { id: 'c', text: 'Third' } ]; function ListWithIndexKey() { const [items, setItems] = useState(initialItems); function shuffle() { setItems(items.slice().reverse()); } return ( <> <button onClick={shuffle}>Reverse List</button> <ul> {items.map((item, index) => ( <li key={index}> <input defaultValue={item.text} /> </li> ))} </ul> </> ); } export default ListWithIndexKey;
Output
<button>Reverse List</button><ul><li><input value="First" /></li><li><input value="Second" /></li><li><input value="Third" /></li></ul>
Common Pitfalls
Using index as key can cause these problems:
- Incorrect component reuse when list order changes.
- Input fields losing focus or showing wrong values.
- Animations or transitions behaving unexpectedly.
Better to use unique IDs that stay the same even if list order changes.
jsx
const items = [ { id: 'x1', name: 'Item 1' }, { id: 'x2', name: 'Item 2' } ]; // Wrong way (using index as key) items.map((item, index) => <div key={index}>{item.name}</div>); // Right way (using unique id as key) items.map(item => <div key={item.id}>{item.name}</div>);
Quick Reference
- Do: Use unique, stable IDs as keys.
- Don't: Use array index as key if list can reorder or change.
- Why: Keys help React track items for efficient updates.
- Exception: Using index as key is okay if list is static and never changes.
Key Takeaways
Never use array index as key if list items can reorder, add, or remove.
Always use unique and stable IDs as keys to help React track elements correctly.
Using index as key can cause UI bugs like wrong item updates or lost input focus.
Index keys are only safe for static lists that never change order or length.