UUID Reference
UUID is a library for generating RFC-compliant universally unique identifiers. Use it to create unique IDs for items, records, or any entity that needs a guaranteed unique identifier.
Import
import { Trash2 } from "lucide-react";
interface Note {
id: string;
content: string;
createdAt: string;
}
export default function App() {
const [notes, setNotes] = usePersistentItem<Note[]>("notes", []);
const [input, setInput] = React.useState("");
const addNote = () => {
if (!input.trim()) return;
const newNote: Note = {
id: uuidv4(),
content: input.trim(),
createdAt: new Date().toISOString(),
};
setNotes(prev => [newNote, ...prev]);
setInput("");
};
const deleteNote = (id: string) => {
setNotes(prev => prev.filter(n => n.id !== id));
};
return (
<div>
<div className="flex gap-2">
<input
value={input}
onChange={e => setInput(e.target.value)}
placeholder="New note..."
onKeyDown={e => e.key === "Enter" && addNote()}
/>
<button onClick={addNote}>Add</button>
</div>
{notes.map(note => (
<div key={note.id}>
<div className="pt-4 flex items-start justify-between gap-2">
<p className="flex-1">{note.content}</p>
<button variant="ghost" size="icon" onClick={() => deleteNote(note.id)}>
<Trash2 className="w-4 h-4" />
</button>
</div>
</div>
))}
</div>
);
}
When to Use UUIDs
Use UUIDs for:
- Unique identifiers for user-created items (tasks, notes, records)
- IDs that need to be generated client-side before syncing
- Keys for React list items when no natural ID exists
Alternatives:
Date.now()- Simple but can collide with rapid creation- Auto-incrementing numbers - Requires tracking the next ID
crypto.randomUUID()- Built-in browser API, same result
Best Practices
- Generate IDs at creation time - Don't generate in render functions
- Use as React keys - UUIDs make excellent list keys
- Store as strings - UUIDs are always string type
- Trust that generated UUIDs are valid (do NOT parse/validate in UI)