FluentUI Compat

Home > @cascadiacollections/fluentui-compat > useId

useId() function

Hook to generate a stable unique ID for the component instance.

This hook provides a consistent way to generate IDs for accessibility attributes and form elements. The generated ID is: - **Stable**: Never changes across renders for the same component instance - **Unique**: Guaranteed unique across all components using this hook - **Predictable**: Uses an optional prefix for easier debugging - **SSR-compatible**: Works correctly with server-side rendering

**Use cases**: - Linking form labels to inputs via htmlFor and id - ARIA attributes like aria-labelledby, aria-describedby - Creating unique identifiers for DOM elements - Managing focus and accessibility relationships

**React 18+ Alternative**: For React 18+, consider using the built-in useId() hook. This implementation is provided for React 16 and 17 compatibility.

Signature:

export declare function useId(prefix?: string): string;

Parameters

Parameter

Type

Description

prefix

string

(Optional) Optional prefix for the generated ID (default: 'id')

Returns:

string

A stable unique ID string

Example 1

// Basic usage with form fields
function TextField() {
  const inputId = useId('text-field');

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

Example 2

// ARIA relationships
function Tooltip() {
  const tooltipId = useId('tooltip');
  const triggerId = useId('trigger');

  return (
    <>
      <button
        id={triggerId}
        aria-describedby={tooltipId}
      >
        Hover me
      </button>
      <div id={tooltipId} role="tooltip">
        Helpful information
      </div>
    </>
  );
}

Example 3

// Multiple IDs in one component
function FormField() {
  const labelId = useId('label');
  const inputId = useId('input');
  const errorId = useId('error');

  const hasError = true;

  return (
    <div>
      <label id={labelId} htmlFor={inputId}>
        Email
      </label>
      <input
        id={inputId}
        aria-labelledby={labelId}
        aria-describedby={hasError ? errorId : undefined}
        aria-invalid={hasError}
      />
      {hasError && (
        <span id={errorId} role="alert">
          Invalid email address
        </span>
      )}
    </div>
  );
}
  • Edit this page
In this article
Back to top FluentUI React complimentary components and utilities focused on render performance