Sobes.tech
Senior

Why can using the array index as a key cause problems?

sobes.tech AI

Answer from AI

Using an array index as a key (for example, in React when rendering lists) can lead to performance issues and bugs in the interface. This is because when the array changes (adding, removing, or reordering elements), the indices change, and React cannot correctly match elements with their states.

As a result, unnecessary re-renders, focus loss, and component state resets may occur.

It is better to use unique and stable identifiers for elements, such as an id from the data:

const list = [{id: 'a1', name: 'Item 1'}, {id: 'b2', name: 'Item 2'}];

return list.map(item => <div key={item.id}>{item.name}</div>);

This ensures correct element matching during updates.