Current section: Unique IDs 29 exercises
lesson

Intro to Unique IDs

Loading lesson

Transcript

00:00 On the web, you need IDs, not for your data. Well, of course, you need IDs for your data. But what I'm talking about is the IDs that you need for forms and just identifying different parts of the page. Sometimes those IDs are difficult because they need to be unique. You can't have multiple IDs that have

00:19 the same string of characters, which is a problem when you have reusable components. And so you've got, like, here's my input component, and it's got an ID, and maybe it has its label in it and stuff. And so now you have to render that, but maybe you have, like, three of those.

00:37 And so you have to make sure they each have a different ID. And it can be a pain when the actual ID, the value of the ID, doesn't matter. You could just generate it randomly. But the problem with generating it randomly is if you render it on the server as HTML, and then it shows up in the browser, and then you are going to hydrate it with React.

00:56 And so that means attaching all the event handlers and rendering updates on the client. The ID that you randomly generate on the client could be different from the one that you generate on the server. And that is a hydration mismatch, which can cause a number of issues we can talk about later. So because of this, you don't want to just, like,

01:16 randomly generate an ID and, like, if you put that in your render method here and stuff, it would be different every time. It's problems with server rendering, all that. Instead, you can just say, hey, React, can you give me an ID? Just give me any ID. I don't really care what it is. It doesn't matter. I'm just going to use this ID to associate a label and its input.

01:35 And that's what the use ID hook is. It's actually a really simple one. This will be a pretty quick exercise. But you get your use ID. Now you have an ID that you can use. Pass it to your HTML4, pass it to your ID, and poof. Now you have an ID that's guaranteed to be unique on the page.

01:53 And also, you're not going to have any problems with, like, having to remember, oh, yeah, I've got to pass an ID to this thing. And I've got to make it unique. And I've got to think of an name for it. Ah, I don't like doing that. So yeah, it's going to be unique for the React app. And not going to clash with anything.

02:09 So that is what you're going to be working on in this exercise. Let's continue.