Lists and Keys β Rendering Arrays in React
After this topic, you will:
Understand how to render arrays in React and the role of keys.
Rendering Lists with map
To display array data on the screen, use the map function:
const fruits = ["Apple", "Banana", "Cherry"];
function FruitList() {
return (
<ul>
{fruits.map(fruit => (
<li key={fruit}>{fruit}</li>
))}
</ul>
);
}This transforms each element of the array into JSX. Notice the special key prop.
Why Keys are Necessary
When items are added, deleted, or reordered in a list, React needs to know which items have changed. The key serves as a unique identifier for each item.
Without keys, React compares lists based on their order:
Before: [A, B, C]
After: [X, A, B, C]Without keys, React would think that "the first item changed from A to X, the second item changed from B to A, ..." With keys, React only recognizes that "X was added."
Rules for Keys
// If you have a unique ID β best
{users.map(user => (
<UserCard key={user.id} user={user} />
))}
// If the data doesn't have a unique value β second best
{items.map(item => (
<li key={item.name}>{item.name}</li>
))}Keys must be unique among siblings. Database IDs are the best choice.
Why You Shouldn't Use Index as a Key
// Avoid
{items.map((item, index) => (
<li key={index}>{item}</li>
))}When items are added, deleted, or reordered, the index changes. An item that was "3rd" becomes "2nd" after a deletion. React thinks the keys are the same, so it thinks the items are the same.
Result: Values in input fields might be attached to the wrong items, or animations might behave strangely.
When it's okay to use index:
- When the list is static and never changes.
- When the items don't have state or input fields.
Otherwise, use a unique value as the key.
Keys are Not Props
function UserCard({ key, user }) {
// You can't access the key here!
}Keys are special attributes used internally by React. You cannot access props.key in a child component. If you need the ID, pass it as a separate prop:
<UserCard key={user.id} userId={user.id} user={user} />Key Takeaways
Use
mapto transform an array into JSX and provide a unique key for each item. Keys help React efficiently detect additions, deletions, and movements of items. Use the unique ID of the data as the key. Avoid using index.