Conceptual Question

Why array indices make bad React keys

React Ecosystem

Why array indices make bad React keys

You edit the second item in a list, then delete the first. The edited text now appears next to a different item. The data is correct in React DevTools. Why did the UI keep the wrong draft?

Interview answer

A key identifies an item among its siblings across renders. React uses it together with the component type to match the previous child and preserve its state. An array index identifies a position. When items move, React can reuse the state at that position for a different item. Give each item a stable ID and use it as the key.

Reproduce the bug

Render this list with three todos, type a draft into the second row, and remove the first row. Start with key={index} in the map callback. Then repeat with the stable key shown below.

JSX
import { useState } from 'react';
function TodoRow({ todo, onRemove }) {
const [draft, setDraft] = useState(todo.title);
return (
<li>
<label>
Edit {todo.title}
<input value={draft} onChange={event => setDraft(event.target.value)} />
</label>
<button type="button" onClick={() => onRemove(todo.id)}>Remove</button>
</li>
);
}
function TodoList({ todos, onRemove }) {
return (
<ul>
{todos.map(todo => <TodoRow key={todo.id} todo={todo} onRemove={onRemove} />)}
</ul>
);
}

With index keys, the second todo moves into the first child’s position. That child still has its previous draft because the same type and key matched. The third todo moves into the second position, so it inherits the edited draft. With ID keys, the draft follows its todo through a reorder. If a todo leaves the tree, React discards its local state. Store the draft higher up if you need it to survive filtering the row out and back in.

Pick a key that matches the data

  • Use a database ID or another stable identifier your data already has. A composite key works when each part is stable and their combination is unique among these siblings.
  • For an optimistically created row, generate a client ID when creating the item and keep it as the key after the server acknowledges it. Replacing the key at that point remounts the row and can drop focus or draft state.
  • An index can be reasonable for a fixed list whose order and membership will stay the same. An editable, sorted, or filtered list needs stable identities.
  • Generate IDs outside render. A fresh random key on each render remounts each row, including its inputs. React also consumes key itself, so pass the item ID as a separate prop if the row needs it.

Interview follow-up

Can a changing key ever help? Yes. Change the key deliberately when selecting a different conversation should reset its editor. For a list, keep each row’s key stable as it moves, and change a component’s key only when you intend to reset its identity.

Further reading · React list keys · Preserving and resetting state

Continue with nearby questions from the same topic cluster.