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.
Please note that the useId() hook was added for accessibility considerations, and is not meant to generate keys in React.
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.
š Build a full trivia game app with LangChain
Learn by doing with this FREE ebook! This 35-page guide walks you through every step of building your first fully functional AI-powered app using JavaScript and LangChain.js
š Build a full trivia game app with LangChain
Learn by doing with this FREE ebook! This 35-page guide walks you through every step of building your first fully functional AI-powered app using JavaScript and LangChain.js