Middle
What is the purpose of the key attribute in React when rendering lists?
sobes.tech AI
Answer from AI
The key attribute in React is used for uniquely identifying elements in a list during rendering. This helps React efficiently update and re-render the DOM, minimizing the number of operations.
Without keys, React cannot correctly determine which elements have been added, removed, or changed, which can lead to incorrect rendering or reduced performance.
Example of usage:
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 based on its value.