snippettypescriptreactModeratepending
React useId -- SSR-safe unique IDs for accessibility
Viewed 0 times
React 18+
useIdunique IDarialabelSSRhydration
browsernodejs
Problem
Generating unique IDs for form labels, aria attributes, and list keys in SSR apps causes hydration mismatches because Math.random() or counter-based IDs differ between server and client.
Solution
useId generates stable, unique IDs that are consistent between server and client rendering.
Code Snippets
useId for accessible, SSR-safe IDs
import { useId } from 'react';
function TextField({ label }: { label: string }) {
const id = useId();
return (
<div>
<label htmlFor={id}>{label}</label>
<input id={id} />
</div>
);
}
// Multiple related IDs
function PasswordField() {
const id = useId();
return (
<>
<label htmlFor={`${id}-input`}>Password</label>
<input id={`${id}-input`} type="password"
aria-describedby={`${id}-hint`} />
<p id={`${id}-hint`}>Must be 8+ characters</p>
</>
);
}
// IDs are consistent across SSR and client
// No hydration mismatch!Revisions (0)
No revisions yet.