Why is key Needed in React?
key is a special prop in React used to uniquely identify elements in lists. It helps React properly manage element state when they're added, removed or reordered. This is especially important when working with dynamically changing data.
Why key?
-
Render optimization. When list elements change, React uses
keyto determine which elements changed, were added or removed. This allows React to minimize DOM changes and improve performance. -
Unique identification. Each list element must have a unique
keyso React can properly track and manage each element. This is important for correct display and efficient updates.
key Usage Example
const items = ["apple", "banana", "cherry"];
function FruitList() {
return (
<ul>
{items.map((item, index) => (
<li key={index}>{item}</li>
))}
</ul>
);
}
Don't use index as key:
Using index can lead to incorrect element display when their order changes. It's better to use unique identifiers for key.