View on GitHub

Notes

reference notes

Why does React need keys?

React needs keys to efficiently update lists of elements. When a list of elements is rendered, React needs a way to identify which elements have changed when the list updates. Without keys, React would either have to re-render the entire list (inefficient) or have difficulty identifying which specific items have changed.

Importance of keys:

How to use keys:

<Component key={keyValue} />
// or
<div key={keyValue} />
const todos = [
  { task: "mow the yard", id: uuid() },
  // ...
];

function TodoList() {
  return (
    <ul>
      {todos.map((todo) => (
        <li key={todo.id}>{todo.task}</li>
      ))}
    </ul>
  );
}
const months = ['January', 'February', 'March', ...];

function MonthList() {
  return (
    <ul>
      {months.map((month, index) => (
        <li key={index}>{month}</li>
      ))}
    </ul>
  );
}

Best practices and anti-patterns:

// Bad practice, don't generate keys on the fly
{todos.map((todo) => (
  <li key={uuid()}>{todo.task}</li>
))}

Conclusion:

This understanding of keys is crucial for building efficient and responsive React applications.

Official React docs on keys