Rendering a List
In React, you usually render a list using the .map()
function on an array.
const fruits = ["Apple", "Banana", "Cherry"];
function FruitList() {
return (
<ul>
{
fruits.map((fruit, index) => (
<li key={index}>{fruit}</li>
))}
</ul>
);
}
What is a key
?
key
is a special React prop used to identify elements in a list.
Helps React optimize re-rendering when the list changes.
Without a key, React re-renders everything instead of only what changed.
If you don’t assign a key
to a list element in React, React will still render the list, but you'll get an error in the console.
Warning: Each child in a list should have a unique "key" prop.
Why not always use index
as a key?
Using an index as a key can be problematic in certain scenarios
const todos = ["A", "B", "C"];
// user deletes "B"
If you use the index as the key:
Original keys: 0 = A, 1 = B, 2 = C
After deletion: 0 = A, 1 = C
React thinks "C" (index 1) is still B, it reuses the wrong component, which may cause state bugs in child components.
So, when do I even use an index as a key?
Good use-case (static list)
const menuItems = ["Home", "About", "Contact"];
If the list never changes order or never adds/removes items, using the index as a key is fine.
Best Practice
Always use a unique and stable ID for each item if possible
const users = [
{ id: 1, name: "Alice"},
{ id: 2, name: "Bob" },
{ id: 3, name: "Charlie" }
];
{ users.map(user => (
<UserCard key={user.id} user={user} />
))}
Use theindex as a key only if:
The list is static (won’t change)
The items don’t have a unique ID
You are okay with re-rendering all items on change
Example of a Dynamic List
import { useState } from "react";
function TodoList() {
const [todos, setTodos] = useState([
{ id: 1, text: "Buy milk" },
{ id: 2, text: "Walk dog" },
{ id: 3, text: "Read book" },
]);
const removeTodo = (id) => {
setTodos(todos.filter(todo => todo.id !== id));
};
return (
<ul>
{todos.map(todo => (
<li key={todo.id}>
{todo.text} <button onClick={() => removeTodo(todo.id)}>Delete</button>
</li>
))}
</ul>
);
}
Here, each <li>
has a stable key, so React knows exactly which element to remove.