Quiz

What is the consequence of using array indices as the value for `key`s in React?

Topics
React
Edit on GitHub

TL;DR

Using array indices as the value for keys in React can lead to performance issues and bugs. When the order of items changes, React may not correctly identify which items have changed, leading to unnecessary re-renders or incorrect component updates. It's better to use unique identifiers for keys to ensure React can efficiently manage and update the DOM.


Consequence of using array indices as the value for keys in React

Performance issues

When array indices are used as keys, React may not efficiently update the DOM. If the order of items in the array changes, React will not be able to correctly identify which items have been added, removed, or moved. This can lead to unnecessary re-renders and decreased performance.

Incorrect component updates

Using array indices as keys can cause bugs in your application. For example, if the order of items changes, React may reuse the same component instances for different items, leading to incorrect state and props being passed to components. This can result in unexpected behavior and hard-to-debug issues.

Example

Consider the following example where array indices are used as keys:

const items = ['Item 1', 'Item 2', 'Item 3'];
const List = () => (
<ul>
{items.map((item, index) => (
<li key={index}>{item}</li>
))}
</ul>
);

If the order of items changes, React may not correctly update the DOM, leading to performance issues and potential bugs.

Better approach

Instead of using array indices, use unique identifiers for keys. This ensures that React can efficiently manage and update the DOM.

const items = [
{ id: 1, name: 'Item 1' },
{ id: 2, name: 'Item 2' },
{ id: 3, name: 'Item 3' },
];
const List = () => (
<ul>
{items.map((item) => (
<li key={item.id}>{item.name}</li>
))}
</ul>
);

In this example, using item.id as the key ensures that React can correctly identify and update items when the order changes.

Further reading

Edit on GitHub