Sobes.tech
Middle

What is the purpose of the key attribute when rendering lists? Can the array index be used as a key?

sobes.tech AI

Answer from AI

The key attribute in React is used to uniquely identify elements in a list during rendering. This helps React efficiently update and re-render the DOM, minimizing operations and preserving component state.

Using the array index as a key is possible but not recommended, especially if the order of elements can change or elements can be added/removed. In such cases, it can lead to incorrect element matching and UI bugs.

It is better to use unique and stable identifiers, such as IDs from data:

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

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