uniqueId()
uniqueId(
prefix):string
Generates a unique ID. If prefix is given, the ID is appended to it.
remarque
IDs are unique within the current runtime session.
Parameters
prefix: string = ""
The value to prefix the ID with.
Returns: string
The unique ID string.
Since
2.0.0
Note
Counter resets on page reload or process restart.
Also known as
uid (Radashi) · uniqueId (Lodash, es-toolkit) · ❌ (Remeda, Ramda, Effect, Modern Dash, Antfu)
Example
uniqueId(); // => '1'
uniqueId(); // => '2'
uniqueId('user_'); // => 'user_3'
uniqueId('item_'); // => 'item_4'
// Use case: Generate unique keys for React
const items = data.map(item => ({
...item,
key: uniqueId('item_')
}));
// Use case: Create unique DOM IDs
const modalId = uniqueId('modal_');
How it works?
Generates a unique ID, optionally with a prefix.
Counter Mechanism
Use Cases
IDs are unique within the current runtime session.
Use Cases
React list keys for dynamic content 📌
Generate unique keys for dynamically created list items. Essential when items lack natural unique identifiers.
items.map(item => <Card key={uniqueId('card_')} {...item} />);
// Keys: 'card_1', 'card_2', 'card_3'...
Accessible form elements with unique IDs 📌
Create unique IDs for form elements to associate labels. Critical for accessibility compliance.
const id = uniqueId('field_');
<label htmlFor={id}>Email</label>
<input id={id} type="email" />
Temporary entity IDs before server persistence
Create temporary IDs for optimistic updates before server assigns real IDs.
const tempId = uniqueId('temp_');
todos.push({ id: tempId, text, pending: true });
// Replace with real ID after API response