DEV Community

Cover image for I was wrong about keys and collections
Alejandro Ocampo
Alejandro Ocampo

Posted on • Edited on

I was wrong about keys and collections

Almost every React developer has gone through the Main Concepts documentation from React website.

If you have done that, you must have read chapter 8, which is about Lists and Keys (https://reactjs.org/docs/lists-and-keys.html).

You end up understanding that, to use lists in React properly, you need to make use of a key on your components. But why? Well, there’s a brief explanation in there:

Keys help React identify which items have changed, are added, or are removed. Keys should be given to the elements inside the array to give the elements a stable identity.

Isn’t that easy?

At that moment, if you are like me, you might simply assume that React is going to consider that key in order to render responsibly. I mean, my first thought was:

“OK, I need that because it makes sense, If I have a long collection and I need to modify only one item inside of it, React is going to simply consider that key to re-render that item only.”

Is that your thinking? If not, well-done you are a developer who doesn’t simply assume things.

I don’t know how to explain why I made such assumption but by talking to other developers friends of mine, (I’m not saying this is good) I realized they also thought the same. Why? Because reasons. So, if your assumption was the same I had, keep reading.

Out of the lie I made and I believed

Once you start doing React there might be a time when you start worrying about performance on collections. And believe it or not, you will be amazed by the fact that:

React is going to re-render an entire collection even if you just changed one item inside.

Can’t believe it? See the following example, add a couple todo items and then open the Console and play around with the todo items and you’ll see that in fact each item is re-rendered any time you make a change on the collection:

I know this might be obvious for an experienced react developer, but you will be amazed of the amount of people who believes the same lie I once believed.

That’s it. I will be writing other articles on this react learning journey, so stay tuned. Thanks for reading.

Top comments (0)