v2.3

react-unique-id-generator

Readable. Predictable. SSR-safe.

Zero-dependency unique ID generation for React. Custom strategies, collision detection, ID pools, SSR isolation, stable CSS selectors, performance monitoring, and automation test IDs.

Get Started
npm install react-unique-id-generator
0 Dependencies
16.8+ React
100% Coverage
SSR Safe

What's New in v2.3

Stable CSS selector generation for DOM elements, plus all v2.2 features. Fully backward compatible.

Stable CSS Selectors

generateSelector and useStableSelector build unique, human-readable CSS selectors for any DOM element using IDs, data attributes, ARIA roles, and more.

Custom ID Strategies

Plug in your own ID format with IdStrategy, or use built-in numeric, zero-padded, timestamp, and hash strategies.

Collision Detection

CollisionDetector tracks generated IDs and detects duplicates with configurable warn, throw, or skip actions.

ID Pool Management

IdPool pre-allocates IDs with acquire/release semantics, custom generators, and auto-refill.

SSR Provider

<SSRProvider> with requestId namespaces IDs per request. createSSRIdFactory for non-React server code.

Custom Delimiters

generateDelimitedId and useDelimitedId join prefix, counter, and suffix with any delimiter.

The Problem

React's useId() gives you :r0:. No prefix, no scoping, no control. Global counters leak across SSR requests.

React useId
function Form() {
  const id = useId();          // ":r0:"
  return <input id={id} />;   // no prefix, no control
}
This library
function Form() {
  const id = useUniqueId('email-');  // "email-1"
  return <input id={id} />;         // readable
}

Features

Provider-Scoped

Isolate ID counters per subtree with <IdProvider>. Nested providers, zero collisions.

SSR-Safe

Per-request server ID manager and <SSRProvider>. No cross-request state leaks.

Custom Strategies

Plug in numeric, zero-padded, timestamp, hash, or your own custom IdStrategy.

Collision Detection

Track IDs, detect duplicates with configurable warn/throw/skip actions.

ID Pools

Pre-allocate IDs with acquire/release semantics for high-throughput scenarios.

CSS Selectors

Generate unique, stable CSS selectors for DOM elements. Ideal for analytics, session replay, and test automation.

Automation-Ready

Deterministic data-testid with kebab-case, camelCase, or custom strategies.

Lightweight

Zero dependencies. Tree-shakeable ESM and CJS.

TypeScript

Written in TypeScript. Ships declarations and source maps.

Performance

Tracked IDs with auto-cleanup on unmount. Real-time metrics via useIdMetrics().

Comparison

vs React's built-in useId

Feature This library React useId
Custom prefix/suffixYesNo
Provider-scoped IDsYesNo
SSR-safe with isolationYesPartial
Custom generation strategiesYesNo
Collision detectionYesNo
ID pool managementYesNo
Custom delimitersYesNo
Stable CSS selectorsYesNo
SSR request-scoped providerYesNo
Automation test IDsYesNo
Server ID managerYesNo
Counter resetYesNo
React 16+ supportYes18+ only
Non-component usageYesHooks only
Predictable formatprefix-1:r0:
Secure random IDsYesNo
Performance monitoringYesNo
Zero runtime depsYesBuilt-in

Quick Start

import { IdProvider, useUniqueId } from 'react-unique-id-generator';

function App() {
  return (
    <IdProvider prefix="app-">
      <Form />
    </IdProvider>
  );
}

function Form() {
  const emailId = useUniqueId('email-');      // "email-1"
  const passwordId = useUniqueId('password-'); // "password-2"

  return (
    <form>
      <label htmlFor={emailId}>Email</label>
      <input id={emailId} type="email" />
      <label htmlFor={passwordId}>Password</label>
      <input id={passwordId} type="password" />
    </form>
  );
}
import nextId from 'react-unique-id-generator';

function Field({ label }: { label: string }) {
  const id = nextId('field-');  // "field-1", "field-2", ...

  return (
    <div>
      <label htmlFor={id}>{label}</label>
      <input id={id} type="text" />
    </div>
  );
}

Frameworks

Next.js

<IdProvider> in root layout. createServerIdManager in API routes.

Vite

Zero config. ESM picked up automatically.

CRA

Import and use. CJS and ESM.

Remix / Gatsby

Full SSR support with provider + server manager.

Frequently Asked Questions

Common questions about react-unique-id-generator

What is react-unique-id-generator?

react-unique-id-generator is a lightweight, zero-dependency npm package for generating unique, sequential, and readable IDs in React applications. It provides hooks like useUniqueId, context-based scoping with <IdProvider>, SSR-safe ID generation, custom strategies, collision detection, and ID pool management. It works with React 16.8+ and is fully typed with TypeScript.

How is this different from React's built-in useId?

React's useId (React 18+) generates opaque IDs like :r0: with no customization. react-unique-id-generator gives you readable, prefixed IDs like email-1, works with React 16.8+, supports provider-scoped counters, custom generation strategies (numeric, timestamp, hash), collision detection, ID pools, SSR request isolation, and can be used outside of React components with nextId().

Is it safe to use with server-side rendering (SSR)?

Yes. The library provides multiple SSR-safe approaches: <SSRProvider> with per-request requestId namespacing to prevent cross-request state leaks, createServerIdManager for isolated per-request counters in API routes, and createSSRIdFactory for non-React server code. It works seamlessly with Next.js, Remix, and Gatsby.

Does it have any dependencies?

No. react-unique-id-generator has zero runtime dependencies. React is a peer dependency only. The library ships tree-shakeable ESM and CommonJS bundles, keeping your bundle size minimal. It is built with TypeScript and ships type declarations out of the box.

How do I generate unique IDs for form accessibility (ARIA)?

Use the useUniqueId hook with a descriptive prefix: const id = useUniqueId('email-') generates "email-1". Use this ID in both htmlFor on <label> and id on <input> to create accessible form controls. For multiple IDs, use useUniqueIds to generate a batch. Wrap components in <IdProvider> to scope counters and prevent collisions across different parts of your app.

Can I use custom ID formats or strategies?

Yes. The IdStrategy interface lets you define custom ID formats. Built-in strategies include numericStrategy, zeroPaddedStrategy, timestampStrategy, and hashStrategy. Use generateIdWithStrategy for one-off generation or the useIdWithStrategy hook in components. You can also use generateDelimitedId to join prefix, counter, and suffix with any custom delimiter.