How to Implement React Keys in React
React keys are unique identifiers used by the library to track which items in a list have changed, been added, or been removed. This article provides a straightforward guide on how to implement React keys correctly, explaining their importance for rendering performance, how to apply them in your code, and the best practices for choosing the right key values.
Why React Keys are Necessary
When rendering a list of elements, React needs a way to identify each virtual DOM node. Without keys, if an item’s order changes, React has to re-render every element in the list. By assigning a stable key to each element, React can match the original transitions of elements in the DOM tree, leading to faster updates and preserving local component state (such as input focus or user selections).
How to Implement Keys in a List
To implement keys, assign the key prop to the elements
inside a loop or a .map() function. The key must be a
string or a number that uniquely identifies that specific item among its
siblings.
Here is a basic implementation:
import React from 'react';
function UserList() {
const users = [
{ id: 'user-1', name: 'Alice' },
{ id: 'user-2', name: 'Bob' },
{ id: 'user-3', name: 'Charlie' }
];
return (
<ul>
{users.map((user) => (
<li key={user.id}>
{user.name}
</li>
))}
</ul>
);
}
export default UserList;In this example, user.id is passed to the
key prop of the <li> element. Because
each ID is unique to that user, React can efficiently update the list
when users are added or removed.
Best Practices for Choosing Keys
To ensure optimal performance and avoid rendering bugs, follow these key selection guidelines:
1. Use Unique Database IDs
The best key is a unique string that consistently identifies the
item, such as a database primary key (id), a UUID, or a
slug. These values remain the same across re-renders and data
modifications.
2. Avoid Using Array Indexes
While React allows you to use the array index as a key (e.g.,
key={index}), you should only do this as a last resort. If
the list is filtered, sorted, or items are inserted in the middle, using
the index can cause rendering bugs, slow performance, and loss of
component state.
3. Do Not Generate Keys on the Fly
Never generate keys dynamically during the render cycle using
functions like Math.random() or uuid().
Generating new keys on every render forces React to destroy and recreate
the entire list of DOM elements, causing severe performance issues.
4. Keys Must Be Siblings-Unique
Keys do not need to be globally unique across your entire application. They only need to be unique among sibling elements within the same array.