React: Additional Hooks
Created on: Sep 18, 2024
These are rarely used hooks mostly used in libraries.
1. useId
useId is a React Hook for generating unique IDs that can be passed to accessibility attributes.
It takes no argument and returns a unique id associated with that particular useId call and in that particular component. It shouldn’t be used to generate unique ids for other purpose (other than accessibility attributes).
useId can be used both on server and client.
import { useId } from "react"; function Form() { const id = useId(); return ( <> <label htmlFor={`${id}--firstName`}>First Name</label> <input id={`${id}--firstName`} type="text" placeholder={`Generated id --> ${id}`} /> <label htmlFor={`${id}--lastName`}>Last Name</label> <input id={`${id}--lastName`} type="text" placeholder={`Generated id --> ${id}`} /> <label htmlFor={`${id}--email`}>Email</label> <input id={`${id}--email`} type="email" placeholder={`Generated id --> ${id}`} /> </> ); } export default Form;
The primary benefit of useId is that React ensures that it works with server rendering.During server rendering, our components generate HTML output. Later, on the client, hydration attaches our event handlers to the generated HTML. For hydration to work, the client output must match the server HTML.
2. useDebugValue
useDebugValue
is a React Hook that lets you add a label to a custom Hook in React DevTools.
import { useDebugValue } from "react"; function useOnlineStatus() { // ... useDebugValue(isOnline ? "Online" : "Offline"); // ... }
3. useSyncExternalStore:
It helps components subscribe to external stores.