Tutorial

React Keys and You

Published on December 28, 2018
author

joshtronic

React Keys and You

Keys are an important aspect to rendering collections. React uses component keys to determine which of the components in a collection needs to be re-rendered instead of just re-rendering the entire set of components every time anything changes. This simple but powerful bit of functionality helps keep your React app snappy and that’s a good thing.

Keys are mandatory

Let’s say we have the following code that loops through an array and creates a series of list item components:

const reptiles = ['alligator', 'crocodile', 'snake'];

const reptileComponents = reptiles.map((reptile) => {
  <li>
    {reptile}
  </li>
});

const container = document.createElement('div');
document.body.appendChild(container);
ReactROM.render(<ul>{reptileComponents}</ul>, container);

This will cause React to toss a warning into the console advising that each child in an array or iterator should have a unique key.

Thing is, everything still renders correctly, today at least. Since production bundles usually omit these type of warnings, you need to be sure to be mindful of them during development.

Just because React correctly renders the keyless components today doesn’t mean that React will correctly render the keyless components in the future.

To fix the aforementioned code, all you need to do is include a key property on your list items:

const reptiles = ['alligator', 'crocodile', 'snake'];

const reptileComponents = reptiles.map((reptile) => {
  <li key={reptile}>
    {reptile}
  </li>
});

const container = document.createElement('div');
document.body.appendChild(container);
ReactROM.render(<ul>{reptileComponents</ul>, container);

Keys must be unique, but only amongst siblings

Keys help ensure that only the components that have changed get re-rendered. The only way it’s possible to keep track on which components have actually been changed is to tag them with a unique key.

Fortunately, the uniqueness of the keys only applies to the collection itself. Keys do not need to be unique across your entire React app, just unique across the siblings of your collection.

If we were to run the following code, with the addition of another alligator, we would run into a warning:

const reptiles = ['alligator', 'crocodile', 'snake', 'alligator'];

const reptileComponents = reptiles.map((reptile) => {
  <li key={reptile}>
    {reptile}
  </li>
});

const container = document.createElement('div');
document.body.appendChild(container);
ReactROM.render(<ul>{reptileComponents}</ul>, container);

Similar to how the warning about the lack of keys doesn’t actually cause any issues, having duplicate keys still renders correctly today. Internally, the lack of unique keys is probably causing additional re-renders that can slow our app down.

That’s not to say you should ignore the warning, though. The warning additionally mentions that things could change in the future and that YMMV as non-unique keys could result in duplicate and/or omitted components.

To fix this duplicate key issue, a quick fix would be to include the array’s index as the key instead of the value:

const reptiles = ['alligator', 'crocodile', 'snake', 'alligator'];

const reptileComponents = reptiles.map((reptile) => {
  <li key={index}>
    {reptile}
  </li>
});

const container = document.createElement('div');
document.body.appendChild(container);
ReactROM.render(<ul>{reptileComponents</ul>, container);

It’s sufficient in a pinch with a fixed order array, but if the order of the array items may change in the future, it’s not the most ideal solution.

In those scenarios, it would be better to use some sort of internal unique identifier instead (ID).

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

Learn more about our products

About the authors
Default avatar
joshtronic

author

While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.

Still looking for an answer?

Ask a questionSearch for more help

Was this helpful?
 
Leave a comment


This textbox defaults to using Markdown to format your answer.

You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!

Try DigitalOcean for free

Click below to sign up and get $200 of credit to try our products over 60 days!

Sign up

Join the Tech Talk
Success! Thank you! Please check your email for further details.

Please complete your information!

Become a contributor for community

Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.

DigitalOcean Documentation

Full documentation for every DigitalOcean product.

Resources for startups and SMBs

The Wave has everything you need to know about building a business, from raising funding to marketing your product.

Get our newsletter

Stay up to date by signing up for DigitalOcean’s Infrastructure as a Newsletter.

New accounts only. By submitting your email you agree to our Privacy Policy

The developer cloud

Scale up as you grow — whether you're running one virtual machine or ten thousand.

Get started for free

Sign up and get $200 in credit for your first 60 days with DigitalOcean.*

*This promotional offer applies to new accounts only.