generateId Function
December 21, 2025
Generating unique IDs is a common need in React (for keys), forms, and temporary data. Here are several approaches for creating unique identifiers.
// Simple counter-based ID
let idCounter = 0;
export function generateId(prefix: string = 'id'): string {
return `${prefix}-${++idCounter}`;
}
// Timestamp-based ID
export function generateTimestampId(): string {
return `id-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`;
}
// UUID-like string
export function generateUUID(): string {
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (c) => {
const r = (Math.random() * 16) | 0;
const v = c === 'x' ? r : (r & 0x3) | 0x8;
return v.toString(16);
});
}
// Short unique ID
export function generateShortId(): string {
return Math.random().toString(36).substr(2, 9);
}
How It Works
- Counter-based: Simple incrementing counter, not globally unique.
- Timestamp-based: Combines timestamp with random string.
- UUID-like: Follows UUID v4 format (not cryptographically secure).
- Short ID: Random alphanumeric string, shorter but less unique.
Example Usage
// React keys
function ItemList({ items }) {
return (
<ul>
{items.map(item => (
<li key={generateId('item')}>{item.name}</li>
))}
</ul>
);
}
// Form field IDs
const inputId = generateId('input');
<input id={inputId} />
// Temporary data
const tempUser = {
id: generateTimestampId(),
name: 'Guest',
};
Comparison
generateId('user'); // "user-1", "user-2", ...
generateTimestampId(); // "id-1699123456789-k3j2h1g4f"
generateUUID(); // "a1b2c3d4-e5f6-4789-a012-b3c4d5e6f789"
generateShortId(); // "k3j2h1g4f"
Use Cases
- React component keys
- Form field IDs
- Temporary data identifiers
- Client-side ID generation
- Unique file names
Notes
- Counter-based IDs are not unique across page reloads.
- For production, consider using
crypto.randomUUID()(browser API) or libraries likeuuid. - Short IDs are fine for temporary use but not guaranteed unique.
- UUID v4 provides good uniqueness for most use cases.
Choose the right ID generation method based on your needs: simplicity, uniqueness, or format requirements.