What are React Keys in React
In React, keys are unique identifiers used to manage lists of elements efficiently. This article explains what React keys are, why they are crucial for rendering performance, how to use them correctly, and the common pitfalls to avoid when assigning key values in your components.
The Purpose of React Keys
When you render a list of elements in React, the library needs a way to keep track of each individual element. React uses “keys”—which are special string attributes—to identify which items in a list have changed, been added, or been removed. Keys give the elements a stable identity, allowing React’s virtual DOM to reconstruct the UI efficiently during updates.
Without keys, React would have to re-render the entire list whenever a single change occurs. By using keys, React can pinpoint the exact element that changed and update only that specific part of the Document Object Model (DOM), significantly improving application performance.
How React Keys Work (Reconciliation)
React relies on a process called “reconciliation” to update the DOM. When the state of a list changes, React compares the new virtual DOM tree with the previous one.
If a list item has a key, React compares the keys of the new elements to the keys of the old elements: * Matching Keys: React knows the element is the same and only updates its attributes or contents if they have changed. * New Keys: React knows a new element has been added and inserts it into the DOM. * Missing Keys: React knows an element has been removed and deletes it from the DOM.
Best Practices for Choosing Keys
To ensure optimal performance and avoid rendering bugs, follow these best practices when choosing keys:
- Use Unique Identifiers: The best key is a unique
string or number that permanently identifies a list item among its
siblings. Typically, this is an ID generated by your database (e.g.,
user.idorproduct.id). - Avoid Using Array Indexes: While React allows you
to use the array index as a key (e.g.,
key={index}), this is generally discouraged. If the list can be reordered, filtered, or sorted, using the index as a key can lead to rendering bugs, state misalignment in input fields, and poor performance. - Do Not Generate Keys on the Fly: Do not use random
values like
Math.random()or temporary timestamps for keys. Since these values change on every single render, React will destroy and recreate the DOM nodes from scratch during every update, defeating the purpose of keys.
Example of Implementing Keys
Here is a simple example of how to correctly implement keys in a React component:
const TodoList = ({ todos }) => {
return (
<ul>
{todos.map((todo) => (
<li key={todo.id}>
{todo.text}
</li>
))}
</ul>
);
};In this example, each todo item has a unique
id provided by the data source. Using todo.id
as the key ensures that React can accurately track and update each list
item individually.