Keys help React identify which items in a list have changed, been added, or removed. They should be unique among siblings and stable across renders. Using proper keys improves performance and prevents bugs with component state.
Why Keys Matter:
Key Rules:
What to Use as Keys:
function TodoList({ todos }) {
return (
<ul>
{todos.map(todo => (
// Use unique, stable identifier
<li key={todo.id}>
{todo.text}
</li>
))}
</ul>
);
}
// Data with unique IDs
const todos = [
{ id: 1, text: 'Learn React' },
{ id: 2, text: 'Build an app' },
{ id: 3, text: 'Deploy' }
];