Keys in React are used to uniquely identify elements in a list. When React renders a list of components, it needs a way to track each item so it can efficiently update the UI when the list changes. Keys provide this identity and help React optimize rendering.
When a list changes due to items being added, removed, or reordered, React compares the new list with the previous one. Without keys, React relies on the position of elements in the list, which can lead to incorrect updates. With keys, React can accurately determine which elements have changed and update only those parts of the UI.
Basic example without keys:
function ItemList() {
const items = ["Apple", "Banana", "Orange"];
return (
<ul>
{items.map(item => (
<li>{item}</li>
))}
</ul>
);
}
This code will work, but React will show a warning because each list item lacks a key.
Correct example using keys:
function ItemList() {
const items = ["Apple", "Banana", "Orange"];
return (
<ul>
{items.map(item => (
<li key={item}>{item}</li>
))}
</ul>
);
}
Here, each list item has a unique key. React uses this key to track individual elements.
Why Keys Are Important
Keys help React determine which elements are the same between renders. This is especially important for dynamic lists where items can be added, removed, or reordered. Without keys, React may reuse components incorrectly, leading to bugs such as wrong data being displayed or input fields losing focus.
Using Index as a Key
Developers sometimes use the array index as a key. While this works in simple static lists, it is not recommended for dynamic lists.
Example using index:
{items.map((item, index) => (
<li key={index}>{item}</li>
))}
Using index as a key can cause issues when the list changes, such as incorrect rendering or unexpected UI behavior.
Best Practice: Use Stable and Unique IDs
The best practice is to use a stable and unique identifier from your data, such as an ID.
Example:
const users = [
{ id: 1, name: "Akbar" },
{ id: 2, name: "Rahul" }
];
{users.map(user => (
<p key={user.id}>{user.name}</p>
))}
This ensures React can correctly track each element.
Real-World Scenario
In applications like todo lists, dashboards, or tables, items are frequently added, removed, or updated. Using proper keys ensures that animations, form inputs, and component states remain consistent when the UI updates.
Important Notes and Best Practices
Keys should be unique among siblings but do not need to be globally unique. Keys are not passed as props to components; they are used internally by React. Avoid generating random keys on each render, as this defeats the purpose of keys.
In summary, keys in React are essential for efficient list rendering and correct UI updates. Using proper, stable keys improves performance and prevents subtle bugs in dynamic React applications.