Middle+
Why are keys needed in React and why should they be unique?
sobes.tech AI
Answer from AI
Keys (key) in React are needed to identify list elements when they are created, updated, and removed. They help React efficiently update the DOM, minimizing the number of operations.
Why keys should be unique:
- React uses keys to understand which elements have changed, been added, or removed.
- If keys are not unique, React may incorrectly match elements, leading to bugs such as incorrect component states or re-rendering.
Example:
const items = ['apple', 'banana', 'cherry'];
return (
<ul>
{items.map((item, index) => (
<li key={item}>{item}</li> // key is a unique value
))}
</ul>
);
Using the array index as a key is possible, but only if the list does not change dynamically, otherwise it can lead to errors during updates.