~/hackweb.dev
Lists and Keys
Quiz
...

Lists and Keys

beginner · updated Tue Sep 08 2026Contribute

Render arrays of data with lists and understand why keys matter.

Lists and Keys

Use .map() to render arrays of data. Keys help React identify which items changed, added, or removed.

Rendering a List

const fruits = ["Apple", "Banana", "Cherry"];

function FruitList() {
  return (
    <ul>
      {fruits.map((fruit) => (
        <li key={fruit}>{fruit}</li>
      ))}
    </ul>
  );
}

Every item needs a key prop.

Why Keys Matter

React uses keys to track items during re-renders. Without keys, or with bad keys, React can’t efficiently update the list.

// ❌ Without keys — React warns you
{fruits.map((fruit) => <li>{fruit}</li>)}

// ✅ With stable keys
{fruits.map((fruit) => <li key={fruit}>{fruit}</li>)}

Keys enable React to reuse DOM nodes correctly when items reorder or change.

What Makes a Good Key

Use a stable, unique identifier:

const users = [
  { id: 1, name: "Alice" },
  { id: 2, name: "Bob" },
];

{users.map((user) => (
  <li key={user.id}>{user.name}</li>
))}

Good keys: database IDs, UUIDs, unique slugs.

Index as Key — Anti-Pattern

Using array index as a key causes bugs when the list reorders:

// ❌ Bad if list can reorder, add, or remove
{items.map((item, index) => (
  <li key={index}>{item.name}</li>
))}

Only use index as key if the list is static and never reorders.

Key Rules

  • Keys must be unique among siblings, not globally
  • Keys must be stable — don’t generate them with Math.random()
  • Keys can be strings or numbers
  • Don’t use array index if the list can change

Mapping to Components

Pass data as props for cleaner list rendering:

function UserCard({ user }) {
  return <div>{user.name}</div>;
}

function UserList({ users }) {
  return users.map((user) => (
    <UserCard key={user.id} user={user} />
  ));
}

Best Practices

  1. Use unique IDs — Database IDs or UUIDs as keys
  2. Avoid index keys — If list items can reorder or change
  3. Keep keys stable — Never use Date.now() or Math.random()
  4. Extract list items to components — Cleaner and more reusable

Common Mistakes

  1. Using index as key — Causes bugs with reordering
  2. Using random values — Keys change every render, breaking reconciliation
  3. Using non-unique keys — Duplicate keys cause rendering issues
  4. Forgetting keys entirely — React warns and may behave unpredictably