In React, the key prop is essential when rendering lists (like using .map()) to help React identify which items have changed, been added, or removed.
🔹 Purpose of key:
- Helps React optimize rendering and reconciliation.
- Prevents unnecessary re-renders.
- Maintains component state consistency.
🔸 Example:
const users = ['Alice', 'Bob', 'Charlie'];
return (
<ul>
{users.map((user, index) => (
<li key={index}>{user}</li> // 👈 key used here
))}
</ul>
);
💡 Best practice: use unique and stable keys like an ID, not index (to avoid UI bugs during reordering).
🔻 Without a key:
React uses the index, which can cause bugs in:
- Component state mismatch
- Unwanted DOM re-renders
- Performance issues
✅ Summary:
keyensures efficient DOM updates.- Helps React track list items during re-rendering.
- Use unique identifiers (not
index) when possible.