Generating Client-Side IDs
You'll learn how to create stable, unique keys for list items that don't yet have server-generated IDs.
Why Client-Side IDs Matter
Sometimes you need to render a list of items that don't have database IDs yet—like a form with multiple dynamic input fields, a shopping cart before checkout, or a to-do list before syncing with a server. You still need the key prop, but using array indices would be unstable if items can be reordered or removed.
Using Built-In Tools
Modern JavaScript provides crypto.randomUUID() for generating universally unique identifiers:
const newItem = {
id: crypto.randomUUID(), // "9b1deb4d-3b7d-4bad-9bdd-2b0d7b3dcb6d"
text: "New todo"
};
This generates a RFC4122-compliant UUID that's virtually guaranteed to be unique.
Using the uuid Library
For broader browser support or additional UUID versions, install the popular uuid package:
import { v4 as uuidv4 } from 'uuid';
const [items, setItems] = useState([]);
const addItem = () => {
const newItem = {
id: uuidv4(), // Generates a unique ID
text: "New item"
};
setItems([...items, newItem]);
};
return (
<ul>
{items.map(item => (
<li key={item.id}>{item.text}</li>
))}
</ul>
);
The Critical Rule
Generate the ID once when creating the item—never inside the render or map function. If you call uuidv4() during every render, you'll get a different ID each time, defeating the entire purpose of stable keys.
Key Takeaway: Use crypto.randomUUID() or libraries like uuid to generate stable, unique IDs for client-created list items, ensuring React can properly track component identity even without server IDs.