Generating Keys for Client-Side Data
What you'll learn: How to create stable, unique keys when your list items don't come with IDs from a database.
The Problem with Client-Only Data
Sometimes you're working with data that exists only in the browser—maybe user input in a form, temporary UI elements, or data you've constructed on the fly. This data doesn't have database IDs because it's never been saved anywhere. But React still needs stable keys for list rendering.
Solution: ID Generation Libraries
Two common solutions for generating stable IDs on the client:
1. crypto.randomUUID() (built into modern browsers):
const items = [
{ id: crypto.randomUUID(), text: "New item" },
{ id: crypto.randomUUID(), text: "Another item" }
];
2. The nanoid library (smaller, more customizable):
import { nanoid } from 'nanoid';
const items = [
{ id: nanoid(), text: "New item" },
{ id: nanoid(), text: "Another item" }
];
When to Generate IDs
Generate IDs once when creating the data, not during render:
// ✅ Good: Generate ID when creating item
function addItem(text) {
const newItem = { id: nanoid(), text };
setItems([...items, newItem]);
}
// ❌ Bad: Generating during .map() creates unstable keys
items.map(item => <div key={nanoid()}>{item.text}</div>)
Think of these IDs like birth certificates—they're created once and stay with the person forever, not reassigned every time someone checks.
Key Takeaway: When your data lacks natural IDs, use crypto.randomUUID() or nanoid to generate stable, unique keys at creation time, never during rendering.