Why You Should Never, Ever Use Indices As React Keys

Unraveling the mystery of React keys… Here’s how to use them wisely, which means never using an item’s index as its React key.

Dr. Derek Austin 🥳
React in the Real World

--

Photo by Franco Antonio Giovanella on Unsplash

Let’s Agree To Never Use Indices as React Keys 🔑

In React, the key prop is essential to maintaining the performance and stability of your React apps, though most of us learn about it for the first time from a console error message:

“Warning: Each child in an array or iterator should have a unique ‘key’ prop. Check the render method of …”

What the hell, React? Any time you have a list, you need a key??? Well, React uses keys to identify and track the order of elements in a list, helping to efficiently update and render the correct components when changes occur.

Using indices as React keys might seem like a quick and easy solution, but it can lead to unexpected consequences. Let’s explore why using indices as keys is a bad idea and what alternatives you should consider instead.

The Perils of Indices as Keys 🚫

--

--

Dr. Derek Austin 🥳
React in the Real World

Career advice, film reviews, writing tips, and coding with JS / TS, React & Git. Bio: Web dev since '05. BS & MS in Bioinformatics. Doctor of Physical Therapy.