Generate a deterministic id using a Context Provider

Usage no npm install needed!

<script type="module">
  import charlietangoUseId from 'https://cdn.skypack.dev/@charlietango/use-id';



Generate a deterministic id using a ContextProvider. Use this as a way of generating unique ids for input fields, or linking aria fields.

Checkout the Storybook demo.


yarn add @charlietango/use-id


const id = useId(prefix?: string)

The useId hook should ideally be wrapped with the IdProvider. This ensures that the generated ids are deterministic, since the provider gets created once for each instance of the application.

The hook will revert to generating the id as a side effect if the IdProvider is not included. This means you will get back undefined during the initial render.

⚠️ When using the hook to generate an id for an HTML element, make sure you prefix it with fixed string value - otherwise you'll create a global id that's just a number.


import React from 'react'
import useId, { IdProvider } from '@charlietango/use-id'

const LoginForm = () => {
  const id = useId()
  const inputId = `input-${id}`
  const passwordId = `pass-${id}`

  return (
      <label htmlFor={inputId}>Username:</label>
      <input id={inputId} />
      <label htmlFor={passwordId}>Password:</label>
        aria-describedby={passwordId + '-desc'}
      <p role="alert" id={passwordId + '-desc'}>
        Please enter a password.

const App = () => {
  return (
      <LoginForm />

export default App