Skip to main content

uniqueId()

uniqueId(prefix): string

Generates a unique ID. If prefix is given, the ID is appended to it.

note

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