The Importance of Keys in React

Tanner Townsend
3 min readOct 18, 2020

--

How many times have you been trying to render a list and you get this error? What does it really mean?

Error message when no key is specified in a React list

What are Keys?

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 — React Docs

First, we need to understand that keys are for identification and not directly for performance. Keys will impact performance due to how React uses them for DOM updates.

Keys do not need to be globally unique. They just need to be unique among their siblings within the same array.

Can we just use the array index?

In short, no.

We don’t recommend using indexes for keys if the order of items may change. This can negatively impact performance and may cause issues with component state. […] If you choose not to assign an explicit key to list items then React will default to using indexes as keys. — React Docs

List of four items
Removed the original ‘grape’ from the array
Some of the code for the objects above

Process React takes when removing an item from the array:

  1. Remove the item with the key
  2. Update the array (Changing the ids for all of the items in the list after the grape object)
  3. Re-render the rest of the array since the ids all updated
Added the ‘grape’ back but the pear tag is still messed up

Even after re-adding the grape back into the array, the pear input is still messed up. This is what happens if you use the index as the key.

The Solution

Added a short line of code to fix the key problem

The solution is to simply pick a key that will be unique among the other siblings in the array. Most commonly, an item will have an id that can be used as the key. This will make it easier for React to identify the correct item that is being added/removed from the array and not update the incorrect items.

Another option would be to generate a unique id by using an external library. It is NOT recommended to use Math.random() as that will generate a new id every time the component is updated. This would defeat the purpose of using a key as identification.

What if I’m rendering components?

React thought of this too. You do NOT put the key within the components’ <li> but instead on the component itself.

Screenshot showing where to put the key if rendering components

RULE OF THUMB: The elements inside of the map() calls need keys

TL;DR: Use the items unique id or generate a unique id for the keys if there isn’t already a unique id

--

--

Tanner Townsend
Tanner Townsend

Written by Tanner Townsend

Software Engineer | React | Redux | JavaScript | Ruby on Rails

No responses yet