
what is Lists & Keys in React ?
In React, lists are used to display multiple elements dynamically (like items, users, products). When rendering lists, you must use keys to help React track and update the DOM efficiently.
1. Rendering Lists in React
You commonly use the .map() method to loop through an array and render JSX:
Example: Simple List
function App() {
const cities = ['Mumbai', 'Delhi', 'Pune'];
return (
<ul>
{cities.map((city, index) => (
<li key={index}>{city}</li>
))}
</ul>
);
}
2. What is a Key in React?
A key is a special string attribute you must include when creating lists.
Why keys?
- Help React identify which items changed, added, or removed
- Make list updates faster and more efficient
- Avoids unnecessary re-renders
Example: List of Objects with Unique Keys
function UserList() {
const users = [
{ id: 1, name: 'Jigar' },
{ id: 2, name: 'Ami' },
{ id: 3, name: 'Ravi' }
];
return (
<ul>
{users.map(user => (
<li key={user.id}>{user.name}</li> // Use unique ID as key
))}
</ul>
);
}
Why Not Use index as Key Always?
Using index as key is okay only when:
- Items don’t have a unique ID
- List won’t be reordered, filtered, or updated
Otherwise, it can cause bugs (like incorrect item highlighting or unexpected animations).
Best Practices for Keys
DOs | DON'Ts |
---|---|
Use unique IDs if available | Don’t use index unless necessary |
Add key at topmost JSX element | Avoid duplicate keys |
Keep key stable across renders | Don’t generate new keys every time |
Summary
Concept | Description |
---|---|
list | Rendered using .map() |
key | Unique identifier for each list item |
Purpose | Helps React update UI efficiently |
Comments
Add new comment