Composite Keys for Nested Lists
What you'll learn: How to create unique, stable keys for items that appear in nested or grouped list structures by combining multiple identifiers.
The Problem with Simple Keys in Nested Lists
When rendering nested lists—like categories containing products, or folders containing files—a single ID often isn't enough to guarantee uniqueness. A product with id: 5 might exist under multiple categories. If you only use the product ID as the key, React sees duplicate keys and behavior becomes unpredictable.
Building Composite Keys
A composite key combines multiple pieces of information to create a globally unique identifier. The pattern is simple: join the parent ID with the child ID using a separator that won't appear in your IDs (typically a hyphen or underscore).
{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>
))}
Notice the inner list uses ${category.id}-${product.id} as the key. Even if product ID 5 appears in both Category A and Category B, the composite keys "A-5" and "B-5" are distinct.
Why This Matters
Composite keys preserve React's ability to track each item's identity correctly. When you reorder categories or move a product between them, React can distinguish between "Category A's Product 5" and "Category B's Product 5" as separate components with separate state and lifecycle.
Think of it like addressing a room: "5" isn't enough information in a hotel with multiple floors. "Floor-3-Room-5" is unambiguous.
Key Takeaway: When rendering nested lists, create composite keys by combining parent and child identifiers to ensure every rendered item has a globally unique, stable key across the entire component tree.