Understanding React key
Keys give the react elements a stable
identity
Warning in array without key
import React from 'react'
function App() {
const persons = ['mike', 'jason', 'sharky']
return (
<ul>
{persons.map((p) => {
return <li>{p}</li>
})}
</ul>
)
}
React will throw a warning with the code above: Warning: Each child in a list should have a unique "key" prop.
What keys to use?
Keys should be unique and stable
Use index as key ? It may work, but only under some circumstances
Array index is unique across an array.
import React, { useState } from 'react'
function App() {
const persons = ['mike', 'jason', 'sharky']
return (
<ul>
{persons.map((p, index) => {
return <li key={index}>{p}</li>
})}
</ul>
)
}
However, if the order/number of items may change, array index is NOT stable.
Try it yourself: Tick mike and then click the add button. You'll see the check status incorrectly stays with the first position instead of the expected mike.
Stable key
Usually we will have a unique and stable id like property for each record from backend/database.
Try it yourself: Now tick mike and click add. The checkbox correctly stays with mike because each person has a stable id as the key.
Common key anti-patterns
❌ Random values or timestamps
// DON'T DO THIS
{
items.map((item) => <div key={Math.random()}>{item.name}</div>)
}
// OR THIS
{
items.map((item) => <div key={Date.now()}>{item.name}</div>)
}
Random values change identity on each render. Timestamps can change between renders and can also duplicate across siblings created within the same millisecond. Both are unsuitable substitutes for stable item IDs. Changed keys cause remounting and lost local state.
❌ Duplicate keys
// BAD: Multiple items with same key
{
items.map((item) => <div key={item.category}>{item.name}</div>)
}
Duplicate keys confuse React's reconciliation algorithm and can cause incorrect updates or lost state.
Advanced key concepts
Keys in fragments
When returning multiple elements from a component or mapping an array to fragments, you need to add keys to the fragments:
function Glossary({ items }) {
return (
<dl>
{items.map((item) => (
<React.Fragment key={item.id}>
<dt>{item.term}</dt>
<dd>{item.description}</dd>
</React.Fragment>
))}
</dl>
)
}
Keys only need to be unique among siblings
Keys don't need to be globally unique—only unique among their siblings:
function Blog() {
const posts = [{ id: 1, title: 'Post 1' }]
const comments = [{ id: 1, text: 'Comment 1' }] // Same id is fine!
return (
<>
{posts.map((post) => (
<Post key={post.id} {...post} />
))}
{comments.map((comment) => (
<Comment key={comment.id} {...comment} />
))}
</>
)
}
Use key to unmount component
Use case: I have a select and input component. Each the select option changes, reset the input to default state.
Try it yourself: Type something in both inputs, then change the select. The second input (with key) resets because React unmounts and remounts it when the key changes.
Performance implications
Keys are critical for React's reconciliation performance. With proper keys, React can:
- Efficiently reorder existing DOM nodes instead of recreating them
- Preserve component state when items move in a list
- Match each item to the existing component instance when its identity is unchanged
Keys identify items during reconciliation. They do not by themselves skip component renders. Render skipping depends on other mechanisms, such as memoization.
Conclusion
Choose a key from the item's stable identity, usually its database ID, so component state follows the item when the list changes. Keys need to be unique among siblings. Use an index only when items will not be inserted, deleted, or reordered in a way that changes the identity associated with a position.
Change a key deliberately when you want to reset a component's state. For ordinary updates, keep it stable. A key controls identity during reconciliation, but it does not by itself prevent a component from rendering again.