Course contentsShow
← React
Lesson 1260 of 2,39632. Lists and Keys Deep DiveFree lesson

Generating Stable IDs When None Exist

Using libraries like uuid or nanoid to create stable IDs for data that lacks natural unique identifiers.

Generating Stable IDs When None Exist

What you'll learn: How to create stable, unique keys for list items when your data doesn't include natural IDs.

The Problem

Sometimes you receive data without unique identifiers—maybe you're working with a CSV import, a third-party API that returns plain strings, or user-generated content from a simple text area. You need stable keys for React lists, but there's nothing to use.

The Solution: ID Generation Libraries

Libraries like uuid and nanoid generate cryptographically unique identifiers that remain stable across renders. The key is generating these IDs once when the data first arrives, not on every render.

Using uuid

import { v4 as uuidv4 } from 'uuid';

// Generate IDs when data first loads or is created
function processIncomingData(rawItems) {
  return rawItems.map(item => ({
    ...item,
    id: uuidv4() // Generates: "3f7d2a1e-8b9c-4d3e-a1f2-9c8b7d6e5f4a"
  }));
}

function MyList({ items }) {
  return (
    <ul>
      {items.map(item => (
        <li key={item.id}>{item.text}</li>
      ))}
    </ul>
  );
}

Using nanoid (Smaller Alternative)

import { nanoid } from 'nanoid';

const enrichedData = rawData.map(item => ({
  ...item,
  id: nanoid() // Generates: "V1StGXR8_Z5jdHi6B-myT"
}));

Critical Rule: Generate Once

Generate IDs during data fetching, state initialization, or when items are created—never inside the render method. Generating on every render defeats the purpose of stability.

// ❌ Wrong: New ID every render
{items.map(item => <div key={nanoid()}>{item.text}</div>)}

// ✅ Right: ID generated once when item created
const newItem = { text: value, id: nanoid() };
setItems([...items, newItem]);

Key Takeaway: Use uuid or nanoid to generate stable IDs when data lacks natural identifiers, but always generate them once when data is created or loaded, never during rendering.