Understanding Keys And Their Importance In React

What are keys, and why do we need them? Read this article to find out why!

Understanding Keys And Their Importance In React

Introduction

Have you ever come across this warning:

And even after coming across this warning multiple times, you ignored it because it's just a "warning?" If you're guilty of this, you're not the only developer, my friend. But today, it's time to get rid of that guilt by actually understanding what exactly are keys in React and what purpose they have.

What Are Keys?

In simple terms, keys are unique IDs you give to elements/Components so that React can differentiate between them. Just like every lock has a unique key that can "unlock" it, keys enable React to identify items uniquely.

So, does this mean every Component in our Application needs to have a key?

No. As the above warning suggests, each child in the list must have a unique key prop. This means that whenever you are looping through an array of items, you need to specify a unique key to each item of the array so that React can uniquely identify each of the items.

But why do we need to add Keys?

Let’s say we do not use keys. Then what will happen? Will our app break?

No, our app won’t break, but let's say you have a food-container div in which you are rendering a hundred food-item components. Now, when you try to add a new food-item component in the 50th position(the position isn’t important), there is no way for React to know which one is the new component added. It will treat all components as the same and re-render each one of the components again onto the DOM. Your application performance would take a tremendous hit because, as you know, DOM manipulation is considered a very costly operation. Try and add another new food-item component; now React will re-render all 102 new components again.

Here's a piece of code that mimics my above analogy:

const foodItems = ["Biryani", "Noodles", "Masala Dosa", "Gulab Jamun"];

const App = () => {
   return <>
    {foodItems.map((foodItem) => (
        <div>
            <h1>{foodItem}</h1>
        </div>
    ))}
    </>
}

We are mapping through the foodItems array, and we are displaying each food item in h1, which is wrapped inside of a div. So, the way React reads the code is that okay, for the first food item, I need to render a div with an h1 out onto the DOM. For the second food item, again, render a div with an h1 out onto the DOM. The same schpeel for the third and the fourth food items. Now, let's say we add a fifth new food Item, "Panneer". Since all the previous four food items have already been rendered out onto the DOM, simply render the fifth item, right? This is what we want the above code to do.

Instead, what it will do is re-render all five food items because, as I mentioned, there's no way for React to identify which is the new element, and hence, it treats all the items as the same and re-renders everything out onto the DOM.

So, as you probably would have figured out by now, the workaround for this by adding a unique key prop to each child in the list.

This is what the code will look like after adding the key prop:

const foodItems = ["Biryani", "Noodles", "Masala Dosa", "Gulab Jamun"];

const App = () => {
    return <>
    {foodItems.map((foodItem) => (
        <div key={foodItem}>
            <h1>{foodItem}</h1>
        </div>
    ))}
    </>
}

We are adding the key as foodItem because we are assuming each food item in the array would be unique. Normally, what you would be doing is getting data from an API or querying from a database, which will have a unique id associated with it. You can assign each key to this id. This simple addition of key prop will save your application from performing unnecessary re-renders and thus optimize your performance.

Using Index As Key

Using the index (the second argument to the map method) as a key to identify between items of an array uniquely is definitely a workaround, but you need to understand why it is not a recommended practice. When you use index as a key, your criteria for uniquely identifying each item becomes the position of the item in the array. But what if you delete the first item? Then, after deletion, your second item becomes the first, the third item becomes the second, and so on. Therefore, index as a key often leads to subtle and confusing bugs.

Using index as a key should be your fallback option. In case you do not have an id to identify each item in the array uniquely, only then use index as a key.

Rules Of Keys

  • Keys must be unique among siblings. However, it’s okay to use the same keys for JSX nodes in different arrays.

  • Keys must not change or that defeats their purpose! Don’t generate them while rendering.

Conclusion

Keys are a very important concept in React that I believe developers of all levels must grasp. I hope after reading this blog, you won't be ignoring the warning anymore! I hope you found this blog helpful. Until next time.

Adios!

~ Jyothi Swaroop Makena