This course has been updated! We now recommend you take the Complete Intro to React, v7 course.
Transcript from the "Unique List Item Keys" Lesson
>> Brian Holt: So it's saying, hey, I need a key, so let's talk about that for just a second. So how does React work in terms of like rerendering it? Everytime that something changes, it runs the rerender function here, right? So it runs this searchParams function again. I want you to imagine that maybe these options were more complicated.
[00:00:27] Maybe they were deeply of necetries of DOM structures, so let's say I had the ability to resort these options one way or another. Well, what React would typically see is, this is different than it was before, I'm gonna go rerender everything. But if I'm just resorting them into a different order, that would be a lot of a necessary work, quite slow, potentially.
[00:00:52] What would be really useful, is like, hey, React, I just reordered these. I didn't actually create and destroy anything, they're just in a different order now. And the way you can do that is you can say, key = some unique thing about that particular item. In this case they're all strings and I know they're all different.
[00:01:11] So if I say key = [animal] then it's happy, because then it says if dog was here, but now it's down here. It's like I'm just going to take that option, I'm not gonna destroy it, I'm just gonna move it down there, so that's what key does. So it's a little performance thing that's really easy to do.
[00:01:31] So the key here is, it needs to be some sort of unique identifier about that particular object, right? So maybe if you're sorting user objects, you can sort it by the email, or their user ID, or something that's gonna be unique per user. Then if it moves here, and then it moves down here, it is the same thing.
[00:01:47] So that React can tell it's the same thing, makes sense? Now something that's really important is it has to be unique, so if I put 1, right? Now all of these are gonna have a key of 1 and is going to freak out.
>> Brian Holt: It's gonna say, hey, I encountered with the same key 1.
[00:02:09] That doesn't make any sense to me, so it'll do weird things if you do that.
>> Brian Holt: In this case, it actually is rendering them, so good for that, but sometimes it just won't render them. So make sure it is actually unique about them.