Does the key prop still matter?

The key prop is something react will yell at you about if you render a list of elements in loop and don't give each of them a unique key. I need these keys to be able to tell elements apart so I can know which on is which and if you order something or delete an element or add an element, so that I can know what's going on.

The thing is I've been using react for a really long time now, and honestly I've only every had a problem with the key maybe once, twice, because as long as your list is stable and you're careful about regenerating your data every time you re-render, well then usually it just does that right thing.

You see, the usual approach to showing why the key prop is so important is to construct a list that changes over time. Without the key prop react gets confused and starts rendering the wrong date, it removes elements that you weren't expecting it to remove, it adds elements in the wrong place.

So I tried constructing one of those, you can now add new elements at the bottom, you can remove cats. This isn't using the key prop at all, messages come from state, we look through it and without any key prop, render them as message component. Two buttons, the add cat function of [inaudible 00:01:17] creates a new messages list plus another new message remove cat, takes the first half of the list, drops one element and the other half of the list creates a new list and puts that in our state.

When we update state, that re-renders our component and everything is fine, right. If I go on remove cat it highlights the [BoVonRuden 00:01:35] cat, it removes the [BoVonRuden 00:01:37] cat even though it is supposed to be incorrect. Every time it is removing the correct cat.

I don't know what happened with react 16.3, but it seems to have gotten smarter. I've spent an hour almost two hours trying to create an example that doesn't work without the key prop, and I can't, I just can't figure it out. React is too smart for me.

Should you still use a key prop? Yes, definitely. React is still going to yell at you if you don't use a key prop, you are going to see performance benefits from using it, I think. Probably can still figure out a way to make it break without a key prop-

I just, I couldn't figure out how to do-

Know someone who wants to learn React and its whole ecosystem? Share ๐Ÿ‘‡