📌 Introduction to Keys in React

In React, keys are special string attributes that you need to include when creating lists of elements. Keys help React identify which items have changed, been added, or been removed.

Example without keys (not recommended)

const items = ['Apple', 'Banana', 'Cherry'];
const list = items.map(item => <li>{item}</li>);

Example with keys (recommended)

const items = ['Apple', 'Banana', 'Cherry'];
const list = items.map((item, index) => <li key={index}>{item}</li>);

💡 Why Are Keys Important?

Without proper keys, React may:

⚙️ How Keys Work Behind the Scenes

React uses a diffing algorithm to compare the current virtual DOM with the previous one. Keys act as unique identifiers, so React can match existing elements with new ones efficiently.

Example

const list = items.map(item => <li key={item.id}>{item.name}</li>);

When an item’s key matches an existing element’s key, React updates that element instead of removing and re-adding it.

🛠 Best Practices for Choosing Keys

🚫 Common Mistakes with Keys

📝 Summary

Keys in React lists are essential for helping React efficiently update the UI without unnecessary re-renders. They provide stability to list items, preserve component state, and enhance performance. Always choose unique, stable keys from your data to ensure smooth and predictable rendering.