Current section: Rendering Arrays 59 exercises
solution

Focus State

Loading solution

Transcript

00:00 All right, so if I select Pair wait, no, I'm trying to select pair. No pair. Ah, shoot. I want to select pair Okay, I'm gonna just not auto shuffle. Okay, great pair. We selected pair then I auto shuffle Oh great that ruins the selection anyway

00:16 But my point is I cannot follow the the particular item when I don't have a key because as things are moved around React is just thinking. Oh, you're just like updating the value of this or whatever It's just doing its best guess and it cannot preserve my focus state It's like removing the element adding a new one. Whatever it's doing. It's not what I expect it to do

00:36 and so the things like focus state the input values the If you're rendering components instead of inputs than any state that those components are managing all of that is going to just be a mess if you don't use a key and Using an index as the key is actually going to result in the same thing

00:56 most of the time and so well, it is Potentially like make sense. I suppose it's not always going to However, if you have a proper key then react is like oh that data for or that UI for that data moved over here so I can just move that and every like preserve the focus and the

01:19 Whatever selection range there is and so I can actually select this and I could say Do we have a pineapple pine pineapple, there we go Pine apple, there we go. Hooray and I I'm able to do that and make changes to it without worrying about Everything changing on me now. I

01:38 Understand that you're probably not building a UI like this where things are jumping out all over the place on users But it is useful to understand that when you don't use a key properly you end up resetting the state of whatever Elements are being re-rendered and stuff you unmount and remount and it's not efficient

01:57 For react to have to do that and you could definitely have bugs in your user experience as well So there you go hopefully that kind of give you a little bit of more playing around with this to get some idea of Why the key prop is so important