How to Avoid Bad Advice – React Keys

Paul Littlewood
13 Sep 2022
  • React

Everyone learning React will be familiar with this error. The success of rendering a list of items marred by a confusing error left in the console. So you Google the error, find an overwhelmingly upvoted answer from Stack Overflow and use it to fix your code. Something like this:

// Warning - Don't do this!, index) => (
	<li key={index}>

The error goes away and you celebrate 🎉. Unfortunately, this method of assigning the key the array index value, turns out to have potential serious drawbacks. Perhaps even more importantly, copying the solution hasn’t furthered our understanding of the issue – how and why does React use keys when rendering an array of items?

Understanding Keys in React

From the React Docs:

From this, we can see that keys need to be unique and consistent for React to keep track of an item in the DOM.

The example above satisfies the first requirement, but not the second. If we delete an item from our list, the items following it will now be given a new index on re-render. This can lead to React becoming confused and result in the wrong properties being mapped to their corresponding items.

Good Understanding Leads to a Good Solution

Now we understand how things work, we can either work out a solution for ourselves or help us identify which are the good solutions published online. In the case of React Keys the best solution is to use a Unique ID from the data itself.

const myList = [
	{ someProperty: 'foo', uniqueID: 1 },
	{ someProperty: 'bar', uniqueID: 2 },
	{ someProperty: 'baz', uniqueID: 3 },
]; => (
	<li key={item.unqiqueID}>

In this example, we can see that the keys assigned to our items are now both unique and consistent. Even if we delete item ‘bar’, item ‘baz’ will still be given the same key on re-render, allowing React to keep track of it.