When rendering lists in React using .map()
, using keys incorrectly is a common mistake that can lead to performance issues and bugs. Here’s what you need to know:
The Right Way to Use Keys
{items.map(item => (
<ListItem key={item.id} item={item} />
))}
Common Mistakes with Keys
- Using array indices as keys (unless the list is static):
// Bad - if list can change, reorder, or have items added/removed
{items.map((item, index) => (
<ListItem key={index} item={item} />
))}
- Using non-unique keys:
// Bad - keys must be unique among siblings
{items.map(item => (
<ListItem key="same-key" item={item} />
))}
- Generating unstable keys:
// Bad - key changes on every render
{items.map(item => (
<ListItem key={Math.random()} item={item} />
))}
- Missing keys entirely:
// Bad - React will warn about missing keys
{items.map(item => (
<ListItem item={item} />
))}
Best Practices
- Use a unique ID from your data as the key (like
item.id
) - Keys should be stable – don’t regenerate them on each render
- Keys should be predictable – don’t use random values
- Keys only need to be unique among siblings, not globally
- Avoid using indexes unless you have no other option AND the list is static
Why Keys Matter
React uses keys to:
- Identify which items have changed, been added, or removed
- Maintain component state when the list reorders
- Optimize re-rendering performance
Using keys incorrectly can cause:
- Unnecessary re-renders
- Lost component state
- Performance degradation
- Bugs when list items move or change