Faizo

Writing · Preact · Accessibility · Front end

Preact's useId gave my dialogs the same ids as the page behind them

useId in Preact counts per render root, so a dialog rendered in its own root repeats ids already used on the page. How to detect duplicate ids and replace the hook.

Form fields need ids. A <label for> needs one to point at its input, and aria-describedby needs one to connect a field to its hint or error text. In a component you can't hard-code them, because the component may appear twice on a page. That is the job of the useId hook: it hands each component instance an id that is unique in the document.

In my app it didn't. With one particular dialog open, two inputs in the dialog had the same ids as two inputs in the editor behind it. This is the story of how that happens with Preact, what it breaks, and the few lines that replaced the hook.

What it broke

The dialog had a "Message ID" field and a "Thread ID" field. The editor behind it had "Username" and "Avatar URL" fields. Each pair shared an id. Browsers resolve an id reference to the first matching element in document order, and the editor comes first. So:

  • Clicking the "Message ID" label in the dialog focused nothing useful. Its for pointed at the Username field, which sat under the dialog's backdrop.
  • A screen reader announced the dialog's inputs without their labels, and announced the editor's hint text as the description of a dialog field.
  • A validation error in the dialog was attached, as far as assistive technology could tell, to a field on the page behind.

For a sighted mouse user almost nothing looked wrong, which is why it survived for a long time. I found it while checking the dialog's accessibility by hand, by asking the browser which labels each input had:

// In the console, with the dialog open:
document.querySelector('[role="dialog"] input').labels
// → NodeList [] (the label belongs to another element)

Why useId repeats itself

useId can't use a random number. It was designed for server rendering, where the id generated on the server must equal the id generated in the browser during hydration. So the implementation is deterministic: it derives the id from the component's position in the tree and a counter.

In Preact, that counter is stored on the root of the tree being rendered. The ids come out as P0-0, P0-1, P0-2 and so on, in the order components first ask for one. Within a single tree that is unique. The catch is the phrase "a single tree". Every call to render() into a different container starts a new root with a new counter, beginning again at P0-0.

My dialogs are rendered with createPortal into containers attached to <body>, so that they sit above everything and aren't clipped by any ancestor's overflow or stacking context. In React a portal stays part of the tree that created it. In Preact, createPortal lives in the compatibility package and is built on a separate render() into the target container, so for id purposes each portal is its own root. The editor had already handed out P0-0 and P0-1 to its first two fields. The dialog's first two fields asked their own root and received P0-0 and P0-1 too.

Which fields collided depended on render order, so most dialogs were lucky: their early ids matched elements that didn't use labels. This one wasn't.

Detecting duplicate ids

Duplicate ids don't raise an error anywhere. You have to look for them. This snippet lists every id that appears more than once in the current document. Open each dialog and menu in your app and run it:

const counts = new Map();
for (const el of document.querySelectorAll("[id]")) {
  counts.set(el.id, (counts.get(el.id) ?? 0) + 1);
}
console.table([...counts].filter(([, n]) => n > 1));

The same check works as a test helper. I call it at the end of the tests that open a dialog over a rendered page:

export function duplicateIds(root = document) {
  const seen = new Set();
  const dupes = new Set();
  for (const el of root.querySelectorAll("[id]")) {
    if (seen.has(el.id)) dupes.add(el.id);
    seen.add(el.id);
  }
  return [...dupes];
}

expect(duplicateIds()).toEqual([]);

Automated accessibility checkers also flag duplicate ids that are referenced by a label or an ARIA attribute. They only see the state of the page at the moment they run, though, so a scan of the page with every dialog closed reports nothing.

The replacement hook

My app is never server-rendered. There is no hydration, so I don't need ids to be reproducible across two environments. I only need them to be unique within one page load. A counter at module level does that, because a module is evaluated once no matter how many render roots exist:

import { useRef } from "preact/hooks";

let next = 0;

/** An id unique in this document, across every render root. */
export function useUniqueId(prefix = "id") {
  const ref = useRef(null);
  if (ref.current === null) {
    ref.current = prefix + "-" + (next++).toString(36);
  }
  return ref.current;
}

The ref keeps the id stable for the life of the component instance, across re-renders. Every component in the app now uses this hook, and the project's conventions say never to import useId, so the old one doesn't come back through a new component or a copied snippet.

When you can't do this

If your app is server-rendered and hydrated, a module counter is wrong: the server and the browser would count in different orders, and hydration would report mismatches. In that case the options are:

  • Render overlays inside the main tree, positioned with CSS (or the browser's top layer through <dialog> and the Popover API) instead of being moved to another container. They then share the main root and its counter.
  • Prefix per root. Give each separately rendered root a distinct prefix through context and build ids as prefix + useId().
  • Avoid ids where possible. Wrapping an input inside its <label> needs no for attribute at all. ARIA relationships still need ids, so this only removes part of the problem.

React has the same design, with an explicit answer for multiple roots: createRoot takes an identifierPrefix option for exactly this case. If you run more than one React root on a page and use useId, set it.

Summary

  • useId is unique per render root, not per document. Two roots on one page produce the same ids.
  • In Preact a portal counts as its own root, and dialogs are exactly where labelled form fields live.
  • Duplicate ids fail silently: labels and ARIA references resolve to the first match in the document.
  • Check with input.labels and a duplicate-id scan while overlays are open.
  • Without server rendering, a module-level counter is simpler and correct. With it, give each root a prefix.