Skip to main content

Duplicate keys in lists

If the keys (key) in a list are the same, React loses the ability to distinguish elements when updating the Virtual DOM. As a result, unexpected and incorrect UI updates can occur.


Short answer

If the keys are not unique, React:

  • fails to correctly match elements between the old and new Virtual DOM;
  • may re-render elements incorrectly, mixing up order or content;
  • and even lose local state (for example, input text, focus, counters, etc.).

Why this happens

React uses key during reconciliation:

"Which element in the new list corresponds to which element in the old one?"

If two elements have the same key, React thinks it is the same element, even if their data and order are different.


Example of the problem

javascript
function App() { const users = [ { id: 1, name: "Alice" }, { id: 1, name: "Maria" }, // duplicate key! ]; return ( <ul> {users.map(user => ( <li key={user.id}>{user.name}</li> ))} </ul> ); }

What happens:

  • React sees two <li> elements with key="1";
  • during the update it treats them as the same element;
  • so the second one may not render correctly, or React may replace the first with the second without removing/creating a new node.

The result can be unpredictable:

  • the order of elements gets broken;
  • updates do not happen;
  • the state "sticks" to the wrong element.

Example with state

javascript
function Item({ name }) { const [count, setCount] = useState(0); return <button onClick={() => setCount(count + 1)}>{name}: {count}</button>; } function App() { const items = [ { id: 1, name: "Apple" }, { id: 1, name: "Banana" }, // duplicate key! ]; return items.map(item => <Item key={item.id} name={item.name} />); }

Now if you click the "Apple" button, React may update both elements at once or not update the second one at all, because it cannot tell them apart.


React will not throw a fatal error

React will not "break", but a warning will appear in the console:

Warning: Encountered two children with the same key

This is a signal that the Virtual DOM will not be able to update correctly.


What to do correctly

  1. Always give unique and stable keys:
javascript
key={user.id}
  1. If there is no data, you can use a unique identifier:
javascript
key={`${user.name}-${index}`}
  1. Never use the array index if the order can change:
javascript
// Bad key={index}

Summary

SituationWhat happens
Unique keysReact correctly matches elements
Duplicate keysReact confuses elements, loses state
No keysReact uses indexes and warns in the console
Keys change on every renderReact recreates elements from scratch (slow)

Key idea: key is needed so that React knows which Virtual DOM element a particular node belongs to. If keys repeat, React "loses memory" and updates the UI incorrectly.

Short Answer

Interview ready
Premium

A concise answer to help you respond confidently on this topic during an interview.