Keys in React help identify which list items have changed, been added, or been removed. They make the reconciliation process efficient by allowing React to re-render only the modified elements instead of rebuilding the entire list.
What is the significance of keys in lists in React?
Use guided tracks for structured prep, then practice company-specific question sets when you want targeted interview coverage.
Overview
When rendering lists in React using map(), each item should have a unique key prop. Keys help React track elements between renders, improving performance and preventing bugs during dynamic updates or reordering.
function TodoList({ items }) {
return (
<ul>
{items.map((item) => (
<li key={item.id}>{item.text}</li>
))}
</ul>
);
}
Concept | Explanation |
|---|---|
Uniqueness | Each key must be unique among siblings (but not globally). |
Identity Tracking | Helps React distinguish between elements when data changes. |
Reconciliation | Keys optimize the virtual DOM diffing process by mapping elements efficiently. |
Dynamic Updates | Prevents unnecessary re-renders or lost input focus when items reorder. |
Example: Without Keys
When keys are missing, React may reuse components incorrectly, leading to bugs like mismatched states or input fields swapping values.
{items.map((item, index) => (
<li key={index}>{item.text}</li>
))}
Using array indices as keys works for static lists but can cause issues in lists that reorder or update dynamically.
Best Practices
- Use stable and unique identifiers like database IDs for keys.
- Avoid using array indices if the list can change order or length.
- Do not use random or non-deterministic values as keys — React relies on key consistency across renders.
Performance Insight
Keys allow React’s diffing algorithm (reconciliation) to skip unchanged elements and efficiently patch only modified nodes, improving render speed and stability.
Think of keys like labels on moving boxes — without them, React wouldn’t know which box belongs where after reordering.
- Keys uniquely identify list items during rendering.
- They improve performance and prevent re-rendering bugs.
- Use stable, unique values like IDs — avoid indices when possible.