Tutorial

React Keys and You

Published on December 28, 2018
Default avatar

By joshtronic

React Keys and You

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.

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 us


About the authors
Default avatar
joshtronic

author

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!

Get our biweekly newsletter

Sign up for Infrastructure as a Newsletter.

Hollie's Hub for Good

Working on improving health and education, reducing inequality, and spurring economic growth? We'd like to help.

Become a contributor

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

Welcome to the developer cloud

DigitalOcean makes it simple to launch in the cloud and scale up as you grow — whether you're running one virtual machine or ten thousand.

Learn more
DigitalOcean Cloud Control Panel