React Keys & ListsIntermediate
1Question 1 of 1
javascriptWhy are unique keys essential when rendering lists in React and why should you avoid index as a key?
Explanation & Concept
Keys help React identify which items in a list have changed, been added, or been removed during reconciliation.
Using array indices as keys (`key={index}`) causes rendering bugs, incorrect component state retention, and performance penalties when list items are sorted, filtered, or prepended.
Code Example
javascript
// BAD: key={index} causes re-ordering and input focus bugs!
// {todos.map((todo, index) => <TodoItem key={index} {...todo} />)}
// GOOD: Use stable, unique database IDs
export function TodoList({ todos }) {
return (
<ul>
{todos.map((todo) => (
<li key={todo.id} className="py-2">
{todo.title}
</li>
))}
</ul>
);
}How It Works & Key Takeaways
Stable unique keys enable React to move existing DOM nodes during list reordering rather than unnecessarily recreating them.
Mock Test · 1 Questions · Optional
Ready for Error Boundaries?
Take a quick test to evaluate yourself, or move straight to the next module.
Intermediate1 questions