React hooks - useId

React hooks - useId

Photo by RetroSupply on Unsplash

Introduction

Have you ever created a form with multiple input elements and had a problem coming up with unique ids to assign each of them? The useId hook can sort that issue out for you. Let's dive in and see what it is all about.

The useId Hook

Let us consider a scenario where you have an input element with a certain id and you have added a label that is associated with that input element via that id. Now let us say you have multiple such input elements with the same id. Now the problem is that when you click on any label, the focus is on all the input elements sharing the same id.

export default function App() {
    return (
        <form>
            <label htmlFor="input1">Name:</label>
            <input id="input1" placeholder="Enter your Name" />

            <label htmlFor="input2">Email:</label>
            <input id="input2" placeholder="Enter your Email" />

            <label htmlFor="input3">Password:</label>
            <input id="input3" placeholder="Enter your Password" />
        </form>
    );
}

In such a scenario, the useId hook helps us out by generating unique ids that can be provided to multiple input elements rendered on a single page.

Take a look at the example below to understand how it is used.

export default function App() {
    const id = useId(); 

    return (
        <form>
            <label htmlFor=`${id}-name`>Name:</label>
            <input id=`${id}-name` placeholder="Enter your Name" />

            <label htmlFor=`${id}-email`>Email:</label>
            <input id=`${id}-email` placeholder="Enter your Email" />

            <label htmlFor=`${id}-password`>Password:</label>
            <input id=`${id}-password` placeholder="Enter your Password" />
        </form>
    );
}

Now in the example above, each of the input element has a unique id generated by the useId hook.

The issue with the server-side rendering

Usually, if we try to generate ids using Math.random() there could arise an issue where the ids of the input elements could be different on the server side and on the client side. This issue is also resolved by the useId hook. With the use of the useId hook, the ids used on the input elements are the same on both the server as well as on the client side.

Final Thoughts

That's it, folks. The useId is really underrated but it is really useful. I will see you in my next blog. Till then stay safe, be happy, and code furiously!!

You can follow me on Github, or LinkedIn.

Thank you for taking the time to read the blog.