Installation
Install the package along with React:Why Use UIDs?
Unique IDs are crucial for web accessibility:- Form accessibility: Associate labels with inputs using
htmlForandid - ARIA relationships: Link elements with
aria-labelledby,aria-describedby, etc. - Avoid conflicts: Prevent ID collisions when components are reused
- Server-side rendering: Generate consistent IDs across server and client
- Stable IDs: IDs remain consistent across re-renders
API Reference
useUID
Generates a single unique ID.useUIDSeed
Generates a seed function that creates multiple related IDs with a common prefix.UIDFork
Creates a boundary for generating UIDs in isolated component trees.- Portals and modals
- Isolated component trees
- Testing scenarios
uid
A utility function for generating unique IDs outside of React components.item- Any value to generate a UID for
useUID or useUIDSeed) inside React components instead.
Common Patterns
Form Inputs with Labels
Associate labels with inputs for accessibility:Help Text with ARIA
Associate help text with form fields:Error Messages
Associate error messages with form fields:Lists with ARIA Labels
Label lists with headings:Tabs with ARIA
Create accessible tab interfaces:Modal Dialogs
Create accessible modals:Combobox/Autocomplete
Create accessible combobox components:React 18+ Support
The UID Library automatically uses React’s built-inuseId hook when available (React 18+), providing:
- Better server-side rendering support
- Improved hydration handling
- Native React performance optimizations
react-uid library.
No code changes are needed - the library handles this automatically.
TypeScript Support
The library is fully typed:Best Practices
Do
- Use
useUIDfor single IDs in a component - Use
useUIDSeedwhen you need multiple related IDs - Always associate labels with form inputs
- Use ARIA attributes to create relationships between elements
- Use
UIDForkfor portals and isolated trees
Don’t
- Don’t hardcode IDs in reusable components
- Don’t generate IDs outside of hooks in React components
- Don’t create new hooks on every render (hooks should be at the top level)
- Don’t use generic IDs like “input-1” that might conflict
Performance Considerations
Memoization
UIDs are stable across re-renders, so you don’t need to memoize them:Multiple Components
Each component instance gets unique IDs automatically:Version
Current version: 3.0.1Dependencies
react-uid(2.3.3) - Fallback for React versions below 18