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

Better Alternatives: Generating Stable IDs

Practical approaches for creating stable keys: nanoid, uuid, database IDs, or composite keys from data.

Better Alternatives: Generating Stable IDs

What you'll learn: How to create stable, unique keys when your data doesn't come with IDs built-in.

We've seen that index-as-key causes bugs when lists change. But what if your data doesn't have database IDs? You need a way to generate stable keys yourself. The golden rule: generate once, then reuse forever.

Practical Key Generation Strategies

1. Third-Party ID Libraries

Libraries like nanoid or uuid create unique strings perfect for keys:

import { nanoid } from 'nanoid';

// Generate ONCE when creating data, not during render
const newItem = {
  id: nanoid(), // "V1StGXR8_Z5jdHi6B-myT"
  text: 'Buy milk'
};

// Later, in your component:
items.map(item => <li key={item.id}>{item.text}</li>)

Critical: Generate the ID when you create the data item, not every time you render. Otherwise you get a new ID each render, defeating the purpose.

2. Database IDs

Always prefer server-provided IDs when available. They're guaranteed stable and unique.

3. Composite Keys from Data

If items have unique combinations of properties:

const users = [
  { email: 'alice@example.com', role: 'admin' },
  { email: 'bob@example.com', role: 'user' }
];

users.map(user => (
  <li key={user.email}>{user.role}</li>
))

Only works if email is guaranteed unique and never changes.

4. Client-Side ID Assignment

When adding items to state, assign IDs immediately:

const addTodo = (text) => {
  const newTodo = {
    id: nanoid(),
    text: text
  };
  setTodos([...todos, newTodo]);
};

Key Takeaway: Generate stable IDs using nanoid/uuid libraries, database IDs, or unique data properties—always creating IDs once at data creation time, never during rendering.