An index key ties an element's identity to its position, not its data. When the list is reordered, filtered, or has items inserted or removed anywhere except the end, React matches the wrong old element to each new item. Component state, uncontrolled input values, focus and DOM nodes stay at the old position and appear attached to the wrong item. It also causes unnecessary re-renders. Index keys are only safe for static lists whose items have no state.
function Todos() {
const [todos, setTodos] = useState([
{ id: 'a', text: 'Write tests' },
{ id: 'b', text: 'Ship it' },
]);
const addToTop = () =>
setTodos(t => [{ id: crypto.randomUUID(), text: 'New task' }, ...t]);
return (
<>
<button onClick={addToTop}>Add</button>
<ul>
{todos.map((todo, i) => (
<li key={i}>
{todo.text} <input placeholder="notes" />
</li>
))}
</ul>
</>
);
}
Type "urgent" into the notes for "Write tests", then click Add:
React sees key 0 still exists, so it reuses that <li> and its <input> DOM node and only updates the text. "urgent" now sits next to "New task". The same happens with useState inside a row component: state follows the key, not the data.
Use key={todo.id} and React will insert one new <li> at the top and leave the others untouched.
With index keys, inserting at the front changes the props of every row (each index now holds a different item), so every row re-renders and React.memo can't help. With stable keys, only the new row renders, and the rest are moved or kept.
All of these must hold:
Examples: a static breadcrumb, rendered paragraphs of fixed text, skeleton placeholders.
todo.id, user.slug).crypto.randomUUID() in the event handler, as above) and store it with the item.${row.date}-${row.account}), but only if that combination is unique.key={Math.random()}). That remounts every row on every render.react/no-array-index-key) can flag it.Spotted a mistake or a rights concern? Report an issue