The key prop in React is used to uniquely identify elements in a list, helping React efficiently track and update items when the list changes.
It tells React which items have changed, been added, or removed, so it can re-render only the necessary elements, improving performance.
Example
const fruits = ["Apple", "Banana", "Orange"];
function FruitList() {
return (
<ul>
{fruits.map((fruit, index) => (
<li key={fruit}>{fruit}</li> // Unique key for each item
))}
</ul>
);
}
Why It’s Important
Without a unique key, React can get confused about which items changed, causing:
- Incorrect re-renders
- Lost input states
- Performance issues
❌ Bad Example
{items.map((item, index) => (
<li key={index}>{item.name}</li> // Avoid using index as key
))}
Using the array index as a key can cause bugs when items are reordered or deleted.
💡 In Short:
The
keyprop gives React a stable identity for list items, allowing it to efficiently update only changed elements during reconciliation.