Each child should have a unique key
A warning indicating that elements returned in a list mapping lack a unique 'key' attribute.
Usually happens because:
- ☑ Map callback returns JSX without key prop
- ☑ Using array index on dynamic list
- ☑ Key declared on inner child instead of outermost tag
🔍 Quick Checklist:
📊 Where this usually happens (estimated occurrence)
What is Each child should have a unique key?
When rendering a list of components dynamically (e.g., using .map()), React requires a unique key string property on each item to track modifications, additions, and deletions in the Virtual DOM. Omitting keys (or using array indexes which can change) reduces render performance and can cause UI glitches.
Common Causes
- Mapping over an array and returning JSX without adding key attributes.
- Using index numbers as keys when lists are reordered.
- Failing to ensure key IDs are completely unique.
Common Mistakes
- Using index values as keys on arrays that undergo sorting or item filtering operations.
- Placing the key attribute on child tags instead of the parent container returned by the map function.
How to Fix
Framework-Specific Examples
No framework examples required for this informational status.
Wrong: Map without keys
const items = [{ id: 1, name: "A" }, { id: 2, name: "B" }];
return (
<ul>
{items.map(item => <li>{item.name}</li>)}
</ul>
);Correct: Unique ID Keys
const items = [{ id: 1, name: "A" }, { id: 2, name: "B" }];
return (
<ul>
{items.map(item => <li key={item.id}>{item.name}</li>)}
</ul>
);Best Practices
- Utilize database IDs or generate keys using packages (like UUID) if arrays lack unique fields.
Frequently Asked Questions (FAQ)
Q: Why does React need keys?
React uses keys to identify which items have changed, been added, or been removed. This helps the diffing algorithm optimize DOM updates.
Q: Can I use array indexes as keys?
Only as a last resort. If the list is static (never filtered, sorted, or mutated), index keys are safe. Otherwise, they can cause rendering bugs.
Q: Where should the key be declared?
It must be declared on the outermost element returned by your map callback. If using React fragments, use `<React.Fragment key={...}>`.
Q: Do keys need to be globally unique?
No. Keys only need to be unique among their siblings in a specific list, not globally across the entire app.