Unique Keys in Lists in React JS
Unique Keys in Lists is an important concept in React JS used to identify individual elements when rendering collections of data. Keys help React understand which items have been added, removed, or reordered, allowing it to update the user interface correctly. Developers commonly use unique keys when displaying lists of students, products, employees, tasks, and API records.
Learn React JS: JustAcademy React JS Training Course
Register for a demo: Register for React JS Course Demo
1. What Are Unique Keys in React?
A unique key is a special attribute assigned to an element in a rendered list. It helps React distinguish one sibling element from another. A key can be a string or a number, provided it uniquely identifies the item among its siblings.
For example, consider a list of three products. Each product can have its own ID, which can be used as its key.
Example
const products = [
{ id: 101, name: "Laptop" },
{ id: 102, name: "Keyboard" },
{ id: 103, name: "Mouse" }
];
function ProductList() {
return (
<ul>
{products.map((product) => (
<li key={product.id}>
{product.name}
</li>
))}
</ul>
);
}
export default ProductList;
Output
Laptop
Keyboard
Mouse
In this example, the values 101, 102, and 103 uniquely identify the products within the list. React uses these keys to match the products between renders.
2. Why Are Unique Keys Required?
When a React component renders a list, the list may change because items are added, removed, updated, or rearranged. Unique and stable keys help React determine which rendered items correspond to the same data items.
- Identify elements: Each list item has an identifiable key.
- Handle insertions: React can identify newly added items.
- Handle deletions: React can identify which items have been removed.
- Handle reordering: React can match items even when their positions change.
- Preserve component state appropriately: Stable keys help keep state associated with the correct component identity.
- Avoid warnings: Providing keys prevents the missing-key warning for list elements that require them.
- Support maintainable code: Lists can be rendered dynamically without manually assigning each element.
Important: Keys help React reconcile changes correctly. They are not a guarantee that an application will always render faster; their main purpose is to provide stable identity for list elements.
3. How Do Unique Keys Work?
React compares the elements returned by the current render with those from the previous render. Keys help React determine whether an item is the same item, a new item, or an item that has been removed.
Example: Original List
const fruits = [
{ id: 1, name: "Apple" },
{ id: 2, name: "Banana" },
{ id: 3, name: "Orange" }
];
Example: Updated List
const fruits = [
{ id: 4, name: "Mango" },
{ id: 1, name: "Apple" },
{ id: 2, name: "Banana" },
{ id: 3, name: "Orange" }
];
Here, Mango is a new item, while Apple, Banana, and Orange retain their original IDs. React can use those IDs to identify the existing items even though their positions have changed.
Key Concept
A key should identify the item itself, not merely its current position in the array. This is why stable IDs are generally preferred over array indexes for dynamic lists.
4. Using Unique Keys with map()
The JavaScript map() method is commonly used to create lists in React. Each JSX element directly returned by the map() callback should have a suitable key.
Example
function StudentList() {
const students = [
{ id: 1, name: "Rahul" },
{ id: 2, name: "Priya" },
{ id: 3, name: "Amit" }
];
return (
<div>
<h2>Student List</h2>
<ul>
{students.map((student) => (
<li key={student.id}>
{student.name}
</li>
))}
</ul>
</div>
);
}
export default StudentList;
Explanation
- The
students array contains three student objects.
- Each student object has a unique
id.
- The
map() method generates one list item for each student.
- The
key={student.id} attribute identifies each item among its siblings.
- React uses the keys to help reconcile the list when its data changes.
5. Characteristics of a Good React Key
A good key should have three important characteristics: uniqueness among siblings, stability across renders, and a reliable connection to the data item.
| Characteristic |
Meaning |
Example |
| Unique |
Different items in the same list have different keys. |
key={product.id} |
| Stable |
The same item retains the same key between renders. |
A persistent database ID. |
| Data-based |
The key identifies the item rather than its temporary position. |
key={student.studentId} |
Keys do not need to be unique across the entire application. They only need to be unique among sibling elements in the same rendered collection.
6. Using Database IDs as Unique Keys
Database IDs are often the best choice for React keys because they are designed to identify records reliably. When data comes from an API or database, use the ID field if it is stable and unique for the records being displayed.
Example
function EmployeeList() {
const employees = [
{ employeeId: "EMP101", name: "Neha", role: "Developer" },
{ employeeId: "EMP102", name: "Arjun", role: "Designer" },
{ employeeId: "EMP103", name: "Sara", role: "Tester" }
];
return (
<div>
<h2>Employee Directory</h2>
{employees.map((employee) => (
<div key={employee.employeeId}>
<h3>{employee.name}</h3>
<p>Role: {employee.role}</p>
</div>
))}
</div>
);
}
export default EmployeeList;
In this example, each employee's employeeId is used as the key. The employee's name or role can change without requiring a new key, as long as the employee's identity remains the same.
7. Why Should Keys Be Stable?
A stable key does not change when React renders the same data item again. If a key changes unnecessarily, React may treat an existing component as a different component, causing it to be recreated and potentially losing its local state.
Incorrect Example
{products.map((product) => (
<li key={Math.random()}>
{product.name}
</li>
))}
This is incorrect because Math.random() generates a different value during rendering. React cannot reliably match the items with their previous identities.
Correct Example
{products.map((product) => (
<li key={product.id}>
{product.name}
</li>
))}
Here, the product ID remains associated with the same product, allowing React to match it across renders.
8. Unique Keys vs. Array Indexes
An array index is the position of an item in an array, starting from zero. Although indexes can be used as keys in some cases, they are not ideal for lists whose items can move, be inserted, or be deleted.
Example Using Index
function CityList() {
const cities = ["Mumbai", "Pune", "Delhi"];
return (
<ul>
{cities.map((city, index) => (
<li key={index}>{city}</li>
))}
</ul>
);
}
Potential Problem
If a new city is inserted at the beginning, the indexes of the existing cities change. React may then associate the previous component instances with different cities, which can cause incorrect state associations in lists with inputs or stateful child components.
Preferred Approach
const cities = [
{ id: "city-1", name: "Mumbai" },
{ id: "city-2", name: "Pune" },
{ id: "city-3", name: "Delhi" }
];
function CityList() {
return (
<ul>
{cities.map((city) => (
<li key={city.id}>{city.name}</li>
))}
</ul>
);
}
When Is an Index Acceptable?
- The list is static and does not change its order.
- Items are not inserted or deleted in ways that shift existing positions.
- The list does not contain stateful elements that could become associated with the wrong item.
Best practice: Prefer stable IDs whenever possible. An index is not always wrong, but it should be chosen only when the list's behavior makes it safe.
9. Avoid Duplicate Keys
Two sibling items should not share the same key. Duplicate keys make it difficult for React to determine which item corresponds to which previous element and can lead to incorrect updates.
Incorrect Example
const students = [
{ id: 1, name: "Rahul" },
{ id: 1, name: "Priya" },
{ id: 2, name: "Amit" }
];
function StudentList() {
return (
<ul>
{students.map((student) => (
<li key={student.id}>{student.name}</li>
))}
</ul>
);
}
In this example, Rahul and Priya share the same key. This violates the requirement for unique keys among siblings.
Correct Example
const students = [
{ id: 101, name: "Rahul" },
{ id: 102, name: "Priya" },
{ id: 103, name: "Amit" }
];
Each student now has a different ID. In a real application, ensure IDs are assigned and maintained consistently by the data source rather than inventing new IDs during rendering.
10. Using Unique Keys with Reusable Components
When rendering reusable components from an array, the key should be placed on the component element directly returned by the map() method.
Example
function ProductCard({ product }) {
return (
<div>
<h3>{product.name}</h3>
<p>Price: ₹{product.price}</p>
</div>
);
}
function ProductList() {
const products = [
{ id: 1, name: "Laptop", price: 55000 },
{ id: 2, name: "Keyboard", price: 1200 },
{ id: 3, name: "Mouse", price: 600 }
];
return (
<div>
{products.map((product) => (
<ProductCard
key={product.id}
product={product}
/>
))}
</div>
);
}
export default ProductList;
The key is placed on because that is the element returned by map(). Adding a key only to a nested element inside ProductCard does not provide a key to the parent list.
11. Keys Are Not Normal Props
The key attribute is reserved for React's internal use. React does not pass it to a component as an ordinary prop. If a component needs to access the ID, pass it separately.
Incorrect Example
function StudentCard(props) {
return <p>Student ID: {props.key}</p>;
}
<StudentCard key={student.id} student={student} />
Correct Example
function StudentCard({ student, studentId }) {
return (
<p>
Student ID: {studentId} - {student.name}
</p>
);
}
<StudentCard
key={student.id}
student={student}
studentId={student.id}
/>
Here, React uses key to identify the component, while studentId is a regular prop that the component can access.
12. Unique Keys with Filtered Lists
When filtering a list, use the original item's stable key rather than assigning keys based on the filtered list's positions.
Example
function AvailableProducts() {
const products = [
{ id: 1, name: "Laptop", available: true },
{ id: 2, name: "Tablet", available: false },
{ id: 3, name: "Phone", available: true }
];
const availableProducts = products.filter(
(product) => product.available
);
return (
<ul>
{availableProducts.map((product) => (
<li key={product.id}>{product.name}</li>
))}
</ul>
);
}
export default AvailableProducts;
The filter() method selects the available products, while map() creates the list items. Their original IDs remain stable even when some products are not displayed.
13. Unique Keys with React Fragments
Sometimes a single data item needs to render multiple sibling elements without an extra wrapper element. React's Fragment allows you to group those elements and assign a key.
Example
import { Fragment } from "react";
function StudentDetails() {
const students = [
{ id: 1, name: "Rahul", course: "React JS" },
{ id: 2, name: "Priya", course: "JavaScript" }
];
return (
<div>
{students.map((student) => (
<Fragment key={student.id}>
<h3>{student.name}</h3>
<p>Course: {student.course}</p>
</Fragment>
))}
</div>
);
}
export default StudentDetails;
The explicit syntax supports keys without introducing an extra DOM wrapper. The short fragment syntax <>...> does not accept a key prop.
14. Common Mistakes with Unique Keys
| Mistake |
Problem |
Solution |
| Missing keys |
React may show a warning about list children. |
Provide a key for each rendered sibling. |
| Duplicate keys |
React cannot reliably distinguish sibling items. |
Use unique IDs for each item. |
| Random keys |
Keys change on every render, causing unnecessary remounts. |
Use stable IDs from the data. |
| Using indexes for dynamic lists |
State may become associated with the wrong item after reordering. |
Prefer stable data identifiers. |
| Putting the key on a nested child |
The element returned by the list callback still lacks its key. |
Place the key on the outermost returned element. |
Reading props.key |
The special key is not available as a regular prop. |
Pass the ID separately as a prop. |
| Generating IDs during rendering |
Item identity may change between renders. |
Create and persist IDs when the data item is created. |
15. Best Practices for Unique Keys in Lists
- Use stable database IDs or persistent identifiers whenever possible.
- Make sure keys are unique among sibling elements.
- Keep each item's key stable between renders.
- Avoid generating keys using
Math.random() during rendering.
- Use array indexes only when the list is suitably static.
- Place the key on the element or component returned directly by
map().
- Pass IDs separately if a child component needs to access them.
- Use keyed Fragments when one item produces multiple sibling elements.
- Test dynamic lists that support adding, deleting, sorting, and editing items.
- Ensure that the data source itself does not contain duplicate IDs for sibling items.
16. Practical Project: Student Management List
Create a simple student list application that displays student names and courses using stable unique keys.
Example Code
function StudentManagement() {
const students = [
{ id: "ST101", name: "Aarav", course: "React JS" },
{ id: "ST102", name: "Diya", course: "JavaScript" },
{ id: "ST103", name: "Kabir", course: "HTML and CSS" }
];
return (
<div>
<h1>Student Management System</h1>
<ul>
{students.map((student) => (
<li key={student.id}>
<h3>{student.name}</h3>
<p>Student ID: {student.id}</p>
<p>Course: {student.course}</p>
</li>
))}
</ul>
</div>
);
}
export default StudentManagement;
Project Learning Outcomes
- Store records in an array of objects.
- Render data using the
map() method.
- Assign a unique key to every student.
- Understand the difference between a key and a displayed ID.
- Practice the data-driven rendering approach used in React applications.
17. Interview Questions and Answers
Q1. What are unique keys in React?
Answer: Unique keys are special attributes that identify elements among siblings in a rendered list. They help React match items between renders.
Q2. Why should keys be unique?
Answer: Unique keys help React distinguish sibling elements and determine which items have been added, removed, or reordered.
Q3. Do keys need to be unique across the entire application?
Answer: No. Keys only need to be unique among sibling elements in the same rendered collection.
Q4. Why are stable keys important?
Answer: Stable keys let React associate the same data item with the same component identity across renders. Changing keys unnecessarily can cause components to be recreated and local state to be reset.
Q5. Can array indexes be used as keys?
Answer: Yes, for suitable static lists. For lists that can be reordered, inserted into, or deleted from, stable IDs are preferred.
Q6. Why should we avoid Math.random() as a key?
Answer: Random keys change between renders, so React may treat existing items as new components and recreate them unnecessarily.
Q7. Can a key be accessed using props.key?
Answer: No. React reserves the key attribute for internal use. Pass the ID separately if the component needs it.
Q8. Where should a key be placed when rendering components?
Answer: Place the key on the component element returned directly by the parent's map() callback.
Q9. Can we use strings as keys?
Answer: Yes. Keys can be strings or numbers, as long as they are unique among siblings and stable across renders.
Q10. What happens when a key changes?
Answer: React treats the element as having a different identity. The previous component may be unmounted and a new one mounted, which can reset its local state.
18. Practice Exercises
- Create a list of five students with unique IDs and display them using
map().
- Create a product catalog and use each product's ID as its key.
- Build an employee list using a reusable
EmployeeCard component.
- Sort a list of products and verify that stable IDs remain associated with the same products.
- Remove an item from a dynamic list and observe how stable keys help React identify the remaining items.
- Render a filtered list while keeping the original data IDs as keys.
- Display multiple elements for each record using a keyed React Fragment.
19. Quick Revision Checklist
- Understand the purpose of unique keys in React.
- Know why keys should be stable and unique among siblings.
- Use database IDs or persistent identifiers when possible.
- Understand the risks of using array indexes for dynamic lists.
- Avoid random keys and changing keys during rendering.
- Place keys on the outermost element returned by
map().
- Remember that keys are not regular component props.
- Understand how keys work with reusable components, filtering, and Fragments.
- Practice rendering lists whose items can be added, deleted, or reordered.
20. Conclusion
Unique Keys in Lists are essential for reliable React JS list rendering. A good key identifies a data item consistently and helps React reconcile the UI when list contents change. Use stable and unique IDs whenever possible, avoid random keys, and be careful with array indexes in dynamic lists. Following these practices helps prevent incorrect component-state associations and makes React applications easier to maintain.
Explore the JustAcademy React JS Training Course or register for a React JS course demo to learn more.