Back to List

Lists and Keys β€” Displaying Arrays

This explains how to render arrays with map in React, why the key prop is needed, and what happens if you use it incorrectly.

Beginner
|
5min
|
Verified (2026-07)
Progress0/55 (0%)

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:

jsx
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:

text
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

jsx
// 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

jsx
// 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

jsx
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:

jsx
<UserCard key={user.id} userId={user.id} user={user} />

Key Takeaways

Use map to 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.

πŸ’¬ Questions & Comments

0 comments

You can post without signing in. Guest comments cannot be edited or deleted by their author.

0/2000

Loading...