Skip to content

Commit ac0316d

Browse files
authored
[18] Add docs for useId (#4488)
* [18] Add docs for useId * Update based on feedback
1 parent 4b0e1fe commit ac0316d

File tree

1 file changed

+39
-3
lines changed

1 file changed

+39
-3
lines changed

content/docs/hooks-reference.md

+39-3
Original file line numberDiff line numberDiff line change
@@ -534,14 +534,50 @@ TODO: description
534534
### `useId` {#useid}
535535

536536
```js
537-
const id = useId(value);
537+
const id = useId();
538538
```
539539

540-
TODO: description
540+
`useId` is a hook for generating unique IDs that are stable across the server and client, while avoiding hydration mismatches.
541+
542+
For a basic example, pass the `id` directly to the elements that need it:
543+
544+
```js
545+
function Checkbox() {
546+
const id = useId();
547+
return (
548+
<>
549+
<label htmlFor={id}>Do you like React?</label>
550+
<input id={id} type="checkbox" name="react"/>
551+
</>
552+
);
553+
};
554+
```
555+
556+
For multiple IDs in the same component, append a suffix using the same `id`:
557+
558+
```js
559+
function NameFields() {
560+
const id = useId();
561+
return (
562+
<div>
563+
<label htmlFor={id + '-firstName'}>First Name</label>
564+
<div>
565+
<input id={id + '-firstName'} type="text" />
566+
</div>
567+
<label htmlFor={id + '-lastName'}>Last Name</label>
568+
<div>
569+
<input id={id + '-lastName'} type="text" />
570+
</div>
571+
</div>
572+
);
573+
}
574+
```
541575
542576
> Note:
543577
>
544-
> TODO: identifierPrefix
578+
> `useId` generates a string that includes the `:` token. This helps ensure that the token is unique, but is not supported in CSS selectors or APIs like `querySelectorAll`.
579+
>
580+
> `useId` supports an `identifierPrefix` to prevent collisions in multi-root apps. To configure, see the options for [`hydrateRoot`](/docs/react-dom-client.html#hydrateroot) and [`ReactDOMServer`](/docs/react-dom-server.html).
545581
546582
## Library Hooks {#library-hooks}
547583

0 commit comments

Comments
 (0)