use-id

Generate memoized random id
Import

Usage

use-id hook generates random id that persists across renders. Hook is usually used to bind input elements to labels. Generated random id is saved to ref and will not change unless component is unmounted. Hook will use React useId under the hood if it is available (react@>=18.0 is required).

import { useId } from '@mantine/hooks';
function Input({ id }: { id?: string }) {
const uuid = useId(id);
return (
<>
<label htmlFor={uuid}>Input label</label>
<input type="text" id={uuid} />
</>
);
}
// input and label will have id 'my-id'
const withId = <Input id="my-id" />;
// input and label will have random id 'mantine-fZMoF'
const withoutId = <Input />;

Definition

function useId(id: string): string;