HomeBlogReact Random Id

Generate a random ID in React

Published Feb 8, 2023
Updated Nov 4, 2024
1 minutes read

The most recent version of React has a hook called useId that generates a unique ID for you. You can use this hook to generate a unique ID for your label and input elements for example. This will ensure that the label and input elements are associated with each other.

Using the useId hook from React

import { useId } from "react";
 
function Form() {
  const id = useId();
  return (
    <>
      <label htmlFor={id}>Name</label>
      <input id={id} />
    </>
  );
}

Using Math.random to generate a unique ID

Other solution case you use a old version of React, you can use a browser API (e.g the Math API) to generate a unique ID. This will ensure that the label and input elements are associated with each other.

function Form() {
  const id = Math.random().toString(36).substr(2, 9);
  return (
    <>
      <label htmlFor={id}>Name</label>
      <input id={id} />
    </>
  );
}

Using the crypto API to generate a unique ID

You can also use the crypto API:

// Hook
const useId = () => {
  if ('randomUUID' in crypto) {
    return crypto.randomUUID();
  }
  const uint32 = window.crypto.getRandomValues(new Uint32Array(1))[0];
  return uint32.toString(16);
};
 
// Component
function Form() {
  const id = useId();
  return (
    <>
      <label htmlFor={id}>Name</label>
      <input id={id} />
    </>
  );
}

Creating you own version of useId hook

If you're a library author, and support older React version, you can use a custom version of the useId hook.

import React from 'react';
 
export const getRandomId = () => {
  if ('randomUUID' in crypto) {
    return crypto.randomUUID();
  }
  const uint32 = window.crypto.getRandomValues(new Uint32Array(1))[0];
  return uint32.toString(16);
};
 
const isReact18 = React.version.includes('18');
 
export const useIsomorphicId = () => {
  if (isReact18) {
    // eslint-disable-next-line react-hooks/rules-of-hooks
    return React.useId();
  }
  // eslint-disable-next-line react-hooks/rules-of-hooks
  const localId = React.useRef(getRandomId());
  return localId.current;
};
// Form.tsx
import { useIsomorphicId as useId } from "./useId";
 
function Form() {
  const id = useId();
  return (
    <>
      <label htmlFor={id}>Name</label>
      <input id={id} />
    </>
  );
}

References