Middle
Can you use an array index as a key in React? Why is it not recommended?
sobes.tech AI
Answer from AI
Using the array index as a key in React is technically possible but not recommended, especially if the order of elements can change or elements can be added/removed.
Reasons:
- React uses keys to identify elements during DOM updates. If keys are unstable (for example, if the index changes when rearranging), React may incorrectly match elements, leading to UI bugs.
- Using the index can cause components to re-render even if data hasn't changed, reducing performance.
It's better to use unique and stable identifiers from data, such as id:
const items = [
{ id: 'a1', name: 'Item 1' },
{ id: 'b2', name: 'Item 2' },
];
items.map(item => <Item key={item.id} {...item} />)
If there are no unique ids, consider generating unique keys or using the index only when the list is static and does not change.