Skip to main content

What are keys in React?

In React, the term "key" refers to a special attribute used to help React identify which items in a list have changed, been added, or been removed among siblings.

Keys are crucial for optimizing performance and ensuring correct behavior when rendering dynamic lists of elements.

Choosing a Good Key

The best practice is to use a unique identifier from your data (like an ID). For example:

const List = ({ items }) => {
return (
<ul>
{items.map((item) => (
<li key={item.id}>{item.name}</li>
))}
</ul>
);
};

Using a unique ID ensures that React can accurately track each item, even if the order changes or items are added/removed

Why using array index as a key is a bad practice

Using array index as a key is a bad practice because it can lead to unexpected behavior when the list is modified: items added, removed, reordered.

When you use the index, React may confuse which item is which after changes, leading to unnecessary re-renders and potential bugs with component state

If the list is static and will never change, using the index as a key is less problematic, but it's still not ideal

Summary

  • Keys are used to help React identify which items in a list have changed, been added, or been removed
  • Keys are crucial for optimizing performance and ensuring correct behavior when rendering dynamic lists of elements
  • Use a unique identifier from your data as the key
  • Avoid using array index as a key

References