How to Use Key Prop in React: Simple Guide with Examples
In React, use the
key prop to give each element in a list a unique identifier. This helps React track which items changed, were added, or removed, improving rendering performance and avoiding bugs.Syntax
The key prop is added to elements inside a list to uniquely identify them. It is written as key="uniqueValue" inside the element tag.
Example parts:
key: The special prop React uses internally."uniqueValue": A unique string or number for each element.
jsx
const listItems = items.map(item => <li key={item.id}>{item.name}</li>);
Example
This example shows a React component rendering a list of fruits. Each li element has a unique key from the fruit's id. This helps React update only changed items efficiently.
jsx
import React from 'react'; function FruitList() { const fruits = [ { id: 1, name: 'Apple' }, { id: 2, name: 'Banana' }, { id: 3, name: 'Cherry' } ]; return ( <ul> {fruits.map(fruit => ( <li key={fruit.id}>{fruit.name}</li> ))} </ul> ); } export default FruitList;
Output
<ul><li>Apple</li><li>Banana</li><li>Cherry</li></ul>
Common Pitfalls
Common mistakes include:
- Using the array index as
key, which can cause bugs when list items change order or are added/removed. - Using non-unique keys, which confuses React and leads to rendering errors.
- Not providing a
keyat all, causing React to warn and behave inefficiently.
Always use a stable, unique value like an ID from your data.
jsx
/* Wrong way: Using index as key */ const listWrong = items.map((item, index) => <li key={index}>{item.name}</li>); /* Right way: Using unique id as key */ const listRight = items.map(item => <li key={item.id}>{item.name}</li>);
Quick Reference
- Use unique and stable keys: Prefer IDs from your data.
- Do not use array indexes as keys: This can cause UI bugs.
- Keys help React optimize rendering: They track which items changed.
- Keys must be on the element inside the list: Usually on the direct child returned by
map().
Key Takeaways
Always provide a unique and stable
key prop for list elements in React.Avoid using array indexes as keys to prevent rendering bugs.
key helps React identify which items changed for efficient updates.Place the
key on the direct child element inside the list.Missing or duplicate keys cause warnings and can lead to UI issues.