Middle
What is the purpose of the key attribute in React lists?
sobes.tech AI
Answer from AI
The key attribute in React lists is used to uniquely identify elements during rendering. This helps React efficiently update and re-render the DOM, minimizing the number of operations.
Why it is important:
- When the list changes, React compares previous and new elements.
- If keys are unique and stable, React understands which elements have been added, removed, or changed.
- Without keys, React may re-render the entire list, reducing performance.
Example of usage:
const items = ['apple', 'banana', 'cherry'];
function FruitList() {
return (
<ul>
{items.map((item, index) => (
<li key={item}>{item}</li> // key should be unique and consistent
))}
</ul>
);
}
It is recommended to use unique identifiers from data rather than array index to avoid issues when the list changes dynamically.