@instructure/ui-react-utils
Version:
A React utility library made by Instructure Inc.
37 lines • 1.63 kB
TypeScript
/**
* A React hook that provides SSR-safe, hydration-stable ID generation for
* functional components.
*
* This hook is the functional component equivalent of the `withDeterministicId`
* decorator. It is backed by React's built-in {@link https://react.dev/reference/react/useId `useId`},
* which produces the same id on the server and the client for a given position
* in the React tree.
*
* The returned function may be called multiple times with distinct
* `instanceName` values to derive several unique, stable ids from the same
* component instance (e.g. one for an input and one for its messages).
*
* Note: for apps that mount more than one independent React root on the same
* page (including module federation), pass a distinct `identifierPrefix` to each
* `createRoot`/`hydrateRoot` call so ids stay unique across roots.
*
* Read more about it here: [SSR guide](https://instructure.design/#server-side-rendering)
*
* @param componentName - Component name used as a human-readable id prefix.
* @returns A function that generates stable ids. It accepts an optional
* `instanceName` used as the prefix for that specific id.
*
* @example
* ```tsx
* const MyComponent = () => {
* const getId = useDeterministicId('MyComponent')
* const id = getId()
* const messagesId = getId('MyComponent-messages')
* return <div id={id} aria-describedby={messagesId}>Content</div>
* }
* ```
*/
declare function useDeterministicId(componentName: string): (instanceName?: string) => string;
export default useDeterministicId;
export { useDeterministicId };
//# sourceMappingURL=useDeterministicId.d.ts.map