Keys in React – Do we really need them?

So what exactly are these “keys”?

At its very core a key is nothing but a unique identifier to your element. It’s the same as how a student has a roll number or an employee has a unique employee id assigned to them. It’s just another identifier.

Now that we know the what, let’s move onto the why of it.

So why do we need these keys? You might ask.

The app seems to run fine without it, right? Well, in order to update elements, React needs to know which ones have been changed, updated or removed. Keys are the ones to serve this purpose. Under the hood they help React identify which ones need to undergo a re-render.

Now then, let’s move onto the when. So when do we need to use keys?

A typical use case will be when you’re rendering dynamic content like an array or an object.
Let’s take an example and render a simple list of cities.

export default function App() {
  const listOfCities = [
    { id: "city-1", city: "London" },
    { id: "city-2", city: "Paris" },
    { id: "city-3", city: "New York" },
    { id: "city-4", city: "Singapore" },
    { id: "city-5", city: "Tokyo" }
  ];

  return (
    <div className="App">
      {listOfCities.map((city) => (
        <li>{city.city}</li>
      ))}
    </div>
  );
}

If you were to open up the console now, you’d have a warning that looks something like this:

1.PNG

This is because we are rendering a dynamic content without providing a key to it. The fix is pretty self explanatory, you just add a key prop to the element like so:

{listOfCities.map((city) => (
    <li key={city.id}>{city.city}</li>
))}

In doing so we are setting the id of each of the li element to its respective id that we fetch from the object. This would get rid of our error. We now have a key that holds the id of the city, React is now happy again and the warning is gone.

Things to avoid while setting keys.

1. Index

While it does seem like its an easy and simple solution to get rid of that pesky warning message, you should avoid doing so. Assume you wanted to remove Tokyo from the cities, what you would essentially be saying is that the element at index 5 is now at index 4, but react doesn't know about it. So under the hood its going to keep maintain the same state as it was at index 4. Now this is going to lead to a whole host of unwanted behaviors. You might want to watch this video here to get an even better understanding of this concept.

2. Use hard coded or unpredictable keys

Each key has to be different for React to uniquely identify the element. Setting a hard coded key defeats its entire purpose. If you did try it however, you'll get a warning like this:

2.PNG

The same goes if you're trying to use a random id

However, bear in mind that keys only have to be unique among its siblings. You can have the same key across components as long as they are not direct siblings.

Conclusion

So, what can we make out from this article? Let's summarize:

  1. Keys are necessary for React to identify an element.
  2. Keys should not be hard coded or repeating in anyway. Each key has to be unique for React to identify the element.
  3. Avoid using indexes where elements may go through modifications. Indexes can be used only if the list is static but its still not a recommended way of going about it.

Further reading

The official React documentation
Understanding React key props by Kent C. Dodds

Let's connect over at: Twitter