Course contentsShow
← React
Lesson 155 of 2,3965. Lists and KeysFree lesson

Using Database IDs as Keys

Why server-provided IDs are the gold standard for keys when rendering data from APIs or databases.

Using Database IDs as Keys

What you'll learn: Why server-provided IDs are the gold standard for React keys when displaying data from APIs or databases.

The Ideal Key Source

When rendering lists from a backend API or database, those records almost always come with a unique identifier—typically called id, _id, uuid, or similar. These IDs are your best choice for React keys.

Why Database IDs Are Perfect

Database IDs satisfy all three requirements for good keys:

  1. Unique among siblings — Database systems guarantee uniqueness (primary keys, auto-increment IDs, UUIDs)
  2. Stable across renders — The ID doesn't change when you re-fetch or update the data
  3. Tied to the data itself — The ID represents that specific record, not its position

Think of database IDs like Social Security numbers: they permanently identify a person regardless of where they appear in a line or what information about them changes.

The Pattern

const users = [
  { id: 42, name: "Alice" },
  { id: 17, name: "Bob" },
  { id: 99, name: "Charlie" }
];

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

Notice key={user.id}—we use the ID that came from the database. If users reorder, get filtered, or Bob gets deleted, React uses these IDs to track which component represents which user.

Why Not Use Index Here?

Even if you could use index, don't. Database data often gets sorted, filtered, or paginated. The same record might appear at index 2 on one render and index 5 on the next. The database ID stays constant.

Key Takeaway: When rendering data from servers or databases, always use the provided unique identifier as your key—it's stable, guaranteed unique, and semantically correct.