React 18 added a new hook named useId(). Its only scope is to generate unique IDs.
For example, the below React code:
import { useId } from "react";
function App() {
const myId = useId()
// myId will have a value like ':r0:'
return(<div>
<input type="checkbox" id={myId} name="newsletter" />
<label for={myId}>Subscribe to newsletter</label>
</div>)
}
Will output this HTML:
<div>
<input type="checkbox" id=":r0:" name="newsletter">
<label for=":r0:">Subscribe to newsletter</label>
</div>
I find it a nice tool to reduce the mental load of figuring out unique values for id values.
Specifying a prefixes for useId()
You can also specify a prefix to be appended to the result of useId()
by using the ReactDOM.createRoot()
, and also gain some performance improvements for your React components.
import { useId } from "react";
import { createRoot } from 'react-dom/client'
function App() {
const myId = useId()
return(<div>
<input type="checkbox" id={myId} name="newsletter" />
<label for={myId}>Subscribe to newsletter</label>
</div>)
}
const root = createRoot(document.getElementById('root'), {
identifierPrefix: 'my-prefix-for-ids-'
});
root.render(<App />);
In this case, the output for useId()
will be :my-prefix-for-ids-r0:
.
You can checkout here the codepen for this example.
📖 50 Javascript, React and NextJs Projects
Learn by doing with this FREE ebook! Not sure what to build? Dive in with 50 projects with project briefs and wireframes! Choose from 8 project categories and get started right away.
📖 50 Javascript, React and NextJs Projects
Learn by doing with this FREE ebook! Not sure what to build? Dive in with 50 projects with project briefs and wireframes! Choose from 8 project categories and get started right away.