Sobes.tech
Middle

Why is the key attribute needed in React lists?

sobes.tech AI

Answer from AI

The key attribute in React lists is used to help React efficiently update and re-render list items when changes occur. It serves as a unique identifier for each element, allowing React to track which items have been added, removed, or changed.

Without key, React will re-render the entire list, which reduces performance and can lead to component state errors.

Example:

const items = ['apple', 'banana', 'cherry'];

function FruitList() {
  return (
    <ul>
      {items.map((item, index) => (
        <li key={item}>{item}</li>
      ))}
    </ul>
  );
}

Here, key={item} ensures that each list item has a unique key.