In this part, we will learn about react useId hook, React useId hook used to provide unique ID to elements. This hook generates a string which is unique ID for each element and this ID will be on server side as well as at client side. This ID will be string ID which makes it unique and if we perform operations on it then ID will change again and again after every operation done like rerunning application.
Syntax
const id = useId()
React useId
As we talked earlier, this hook generates the string which is the unique ID, So let’s take an example to see generation of ID:
import { useId } from "react";
function App() {
const id1 = useId();
const id2 = useId();
return (
<div className="App">
<p> The id1 is {id1} </p>
<p>The id2 is {id2}</p>
</div>
);
}
export default App;
Here, we have imported useId hook as we do every time, while working with hooks. Okay, we have called useId twice, and we assigned it in to two constant, now if we print these IDs we will get some random IDs.
Output
If we try to comment any of these IDs or do something else with these, and then you rerun these, then IDs will get changed again.
The useId hook takeaways
- useId is a hook
- useId returns string
- useId returns a unique ID for client and server-side.
Example of useId Hook
import { useId } from "react";
import "./styles.css";
export default function App() {
const FullName = useId();
const email = useId();
const term = useId();
return (
<div className="card">
<div>
<label htmlFor={FullName}>Full Name</label>
<input type="text" id={FullName} name="Full Name" /> {" "}
</div>
<div>
<label htmlFor={email}>Enter Email</label>
<input type="email" id={email} name="email" />
</div>
<div>
<input type="checkbox" id={term} name="term" />
<label htmlFor={term}>Agree with term</label>
</div>
<input type="submit" value="Submit" />
</div>
);
}
Output
When to use useId Hook?
So basically, we use this hook when we need to join two JSX elements (for simplicity, JSX is an HTML element in react) like label and input field as we have done in the above example. You can use this hook to provide some unique IDs to elements, but remember you cannot perform styling in CSS file using these IDs.
Check out video reference here: