Skip Main Navigation
Ben IlegboduBen Ilegbodu

New React useOpaqueIdentifier hook coming soon

A quick overview of the newly implemented useOpaqueIdentifier hook and when you would want to use it

Friday, April 17, 2020 ยท 2 min read

As announced by Josh Comeau on twitter today, React in a future version (v16.4.0 maybe?) will have a new utility hook called useOpaqueIdentifier:

I've always needed a safe function like this in React to auto-generate the id of a input field so that I can associate it with a <label>'s for attribute for accessibility and usability purposes. We could use a global running counter or worse, just a random number, but with server-side rendering there was never a guarantee that the ID generated server-side would be the same when the app hydrated client-side. If there is an ID mismatch, then the UI would have to re-render.

So in theory, when the feature is stable, we would use useOpaqueIdentifier like so:

import React, { useOpaqueIdentifier } from 'react'

const TextField = ({ value, onChange, label }) => {
  const id = useOpaqueIdentifier()

  return (
    <div className="text-field__root">
      <label htmlFor={id}>{label}</label>
      <input type="text" id={id} value={value} onChange={onChange} />
    </div>
  )
}

export default TextField

Until the feature is stable, it'll be accessible via unstable_useOpaqueIdentifier on the experimental releases of react:

import React, { unstable_useOpaqueIdentifier } from 'react'

The same hook could be used to generate an ID to associate a non-<label /> with an input using aria-labeledby.

I was wondering what the "opaque" part in the name is supposed to signify. The hook was originally named useUniqueId, which is basically how it's mainly going to be used. So I asked about it:

And of course Twitter came to the rescue:

I still feel that useOpaqueIdentifier has crossed the line into being too "technically correct" where it doesn't convey the actual use case. However, I'm still glad the feature exists! ๐ŸŽ‰

Keep learning my friends. ๐Ÿค“

Subscribe to the Newsletter

Get notified about new blog posts, minishops & other goodies

โ€‹
โ€‹

Hi, I'm Ben Ilegbodu. ๐Ÿ‘‹๐Ÿพ

I'm a Christian, husband, and father of 3, with 15+ years of professional experience developing user interfaces for the Web. I'm a Google Developer Expert Frontend Architect at Stitch Fix, and frontend development teacher. I love helping developers level up their frontend skills.

Discuss on Twitter // Edit on GitHub