Quiz

What is the purpose of the `key` prop in React?

Topics
React
Edit on GitHub

TL;DR

The key prop in React is used to uniquely identify elements in a list. It helps React optimize rendering by efficiently updating and reordering elements. Without a unique key, React may re-render elements unnecessarily, leading to performance issues and bugs.

{items.map(item => (
<ListItem key={item.id} value={item.value} />
))}

What is the purpose of the key prop in React?

Introduction

The key prop is a special attribute you need to include when creating lists of elements in React. It is crucial for helping React identify which items have changed, been added, or removed, thereby optimizing the rendering process.

Why key is important

  1. Efficient updates: React uses the key prop to keep track of elements. When the state of a list changes, React can quickly determine which items need to be re-rendered, added, or removed.
  2. Avoiding bugs: Without unique keys, React may re-render elements unnecessarily or incorrectly, leading to potential bugs in your application.
  3. Performance optimization: By using unique keys, React minimizes the number of DOM operations, making your application faster and more efficient.

How to use the key prop

When rendering a list of elements, you should provide a unique key for each element. This key should be stable, meaning it should not change between renders. Typically, you can use a unique identifier from your data, such as an id.

const items = [
{ id: 1, value: 'Item 1' },
{ id: 2, value: 'Item 2' },
{ id: 3, value: 'Item 3' }
];
function ItemList() {
return (
<ul>
{items.map(item => (
<ListItem key={item.id} value={item.value} />
))}
</ul>
);
}
function ListItem({ value }) {
return <li>{value}</li>;
}

Common mistakes

  1. Using array index as key: While it might be tempting to use the array index as the key, this is not recommended because the index can change if the list is reordered or items are added/removed.
  2. Non-unique keys: Ensure that the keys are unique across the list. Duplicate keys can lead to unexpected behavior and bugs.
// Bad practice: using array index as key
{items.map((item, index) => (
<ListItem key={index} value={item.value} />
))}
// Good practice: using a unique identifier as key
{items.map(item => (
<ListItem key={item.id} value={item.value} />
))}

Further reading

Edit on GitHub