Composite Keys for Nested Lists
What you'll learn: How to create unique, stable keys for items in nested list structures by combining parent and child identifiers.
The Problem with Nested Lists
When you render lists inside other lists (like categories containing products, or threads containing comments), you might encounter key collisions. If each nested list uses simple IDs like 1, 2, 3, the same key might appear multiple times across different parent containers—React will complain because keys must be unique among siblings.
The Composite Key Solution
A composite key combines the parent's identifier with the child's identifier to guarantee uniqueness across the entire nested structure. Think of it like apartment addresses: "Building A, Unit 3" and "Building B, Unit 3" are different locations even though both have "Unit 3."
The pattern is simple: join parent and child IDs with a delimiter:
{categories.map(category => (
<div key={category.id}>
<h2>{category.name}</h2>
<ul>
{category.products.map(product => (
<li key={`${category.id}-${product.id}`}>
{product.name}
</li>
))}
</ul>
</div>
))}
Here, "electronics-42" and "books-42" are distinct even if both categories contain a product with ID 42.
Why This Works
Composite keys are:
- Stable: They don't change between renders (assuming parent and child IDs are stable)
- Unique: The combination prevents collisions across all nesting levels
- Predictable: React can reliably track each element's identity
For deeply nested structures (lists within lists within lists), keep extending the pattern: "level1-level2-level3".
Key Takeaway: Combine parent and child IDs with a delimiter (like ${parentId}-${childId}) to create collision-free keys for nested lists without sacrificing stability.