Sobes.tech
Middle+

Why is the key attribute needed in React? What will happen if the key changes?

sobes.tech AI

Answer from AI

In React, the key attribute is used for uniquely identifying elements in a list during rendering. This helps React efficiently update the DOM by minimizing re-rendering operations and preserving component state.

If the key changes between renders, React treats the element as new, which leads to the removal of the old element and creation of a new one. This can cause loss of local component state and unnecessary DOM operations.

Example:

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

// Correct: key is a unique and stable identifier
items.map(item => <li key={item}>{item}</li>)

// Incorrect: using index as key, especially if order changes
items.map((item, index) => <li key={index}>{item}</li>)

Using stable keys is important for correct and efficient UI updates.

Why is the key attribute needed in React? What will… - sobes.tech