36. What is the useId hook in React and when should it be used?
easy

The useId hook in React is a utility that generates a unique ID for each component instance, helping ensure accessible and conflict-free HTML IDs across components.


Why It Matters:

  • Accessibility: Unique IDs are essential for associating labels and hints with form fields using attributes like aria-describedby.
  • Reusability: In applications with multiple instances of the same component, useId helps prevent ID collisions.

Key Concepts of useId

  • Identifier Generation: useId automatically generates a stable and unique ID string for each component instance.
  • Prefix Support: You can add a custom prefix or suffix to your ID to avoid clashes across different components or contexts.
  • SSR Friendly: Unlike older techniques like incrementing counters, useId is compatible with server-side rendering, avoiding hydration mismatches.

Example: Using useId in a Password Field

import { useId } from 'react';

function PasswordField() {
  const passwordHintId = useId();
  return (
    <>
      <label>
        Password:
        <input
          type="password"
          aria-describedby={passwordHintId}
        />
      </label>
      <p id={passwordHintId}>
        The password should contain at least 18 characters
      </p>
    </>
  );
}

In this example, useId generates a unique ID for the paragraph that describes the password input. This ID is then referenced in the aria-describedby attribute of the input field, making it accessible to screen readers.


Conclusion

The useId hook in React ensures that elements have consistent and unique IDs across renders and environments, including server-side rendering. This enhances both accessibility and code robustness when building reusable components.