Shahadat Robin
The useId() hook is a new way to generate an ID for both the client and server side in React 18.
Before React 18, there was a similar hook called useOpaqueIdentifier
, but this presented many bugs and limitations. useId is the improved version.
Index
- Isomorphism in React
- What problem is solved with useId?
- Introduction to useId()
- Conclusion
Isomorphism in React
An isomorphic app is one that shares almost all of its code between the server and the client. Let’s recap very quickly what client and server-side stand for.
Client-side rendering
In client-side rendering, the app is loaded by the client. According to how much data is sent from the server, the process may take a long time and this is not ideal for our users.
Server-side rendering
However, when using server-side rendering, the server sends out-of-the-box data ready to display on the screen. Improving significantly the user experience and performance.
React runs on both sides (client and server). That’s why Next.js, for example, improves performance using SSR.
What problem is solved with useId?
When you work with form, for example. You link several HTML elements with an ID. Something like this.
This is ideal. However, sometimes you are not able to do so. You work with dynamic and complex apps. Therefore, a common solution to “solve” this problem tend to be something similar to the following.
The problem lies when your app is executed on both sides (client and server) because the ID will not be the same. Hence, at the moment we want to link the apps from both sides (sometimes for sake of accessibility), they are virtually different. In those cases is when you want to use useId
instead.
Introduction to useId()
With this hook, you are going to be able to generate a really unique ID and if your app is executed on both sides, there will be the same.
In case you have more than one input box, you do not need to use more than one useId
. In other words, you can use only one ID for a whole form using prefixes.
Conclusion
React 18 major changes are those related to performance and UX improvements. As some of the performance techniques are based on SSR, it would be common for you to tackle the ID problem mentioned above.
So, it makes sense this new hook had been introduced with this new version.
Shahadat Robin
Front-End Developer