Fixing React ID Generation with useId

Stop using Math.random() for IDs in React 👇. We often need unique IDs to connect a <label> to an <input> for accessibility. "Clicking the label should focus the input." But generating these IDs is harder than it looks. ❌ The Old Way: 1. Hardcoding (id="email"): Breaks if you render the component twice (duplicate ID error). 2. Random (Math.random()): Breaks Next.js Hydration. The server generates 0.123 and the client generates 0.789. React crashes. ✅ The Modern Way: Use useId. React generates a unique string (like :r0:) that is: • Stable: It matches perfectly during Server-Side Rendering (SSR) and Client Hydration. • Unique: You can render the component 50 times, and each one gets a unique ID. • Prefixable: You can combine it (${id}-error, ${id}-desc) for multiple related elements. The Shift: We are moving from "Manual Strings" to "Deterministic Generation." #ReactJS #NextJS #WebDevelopment #Accessibility #a11y #Frontend #JavaScript #CleanCode #TechTips #Tips #ReactTips #DeveloperTips #ReactHooks

  • text

You don't need to call useId multiple times in one component! If you need IDs for an input, a helper text, and an error message, just use one base ID: const id = useId(); id={id} aria-describedby={${id}-hint} It keeps your DOM clean and connected

Most important : useId hook Should not be used to generate keys in a list.

Who are using Math.random() for ID? That could return the same result

Like
Reply

For most cases I’d rather put the <input> tag inside the <label>, avoiding the need of using any Id whatsoever.

Like
Reply

You should also allow the developer to use their own ID. const inputId = props.id || useId();

In React, if you want to access a specific person (or any item) using a URL parameter, you use useParams() from React Router.

useId really feels like one of those small APIs that quietly saves you from big SSR headaches — especially in Next.js apps where hydration mismatches can get messy fast. Love the “deterministic generation” mindset shift.

See more comments

To view or add a comment, sign in

Explore content categories