Warning Messages in React: Unique Key Props

Getting started with uuid.

Alyssa Lerner First
2 min readDec 28, 2020

If you’ve ever built an app with React.js, you’ve probably encountered the following message:

Warning: Each child in a list should have a unique “key” prop.

This isn’t an issue you’ll generally encounter in vanilla JavaScript, where you wouldn’t typically use props, so it might seem kind of confusing at first. Luckily, there’s a fairly simple workaround.

The issue arises when you’re creating multiple child components. If you’re at all familiar with web development, you’ll know that there’s a hierarchy involved in arranging the elements of a web page. If you have an html table, for example, each row will be a child of the table, and each cell will be a child of its parent row.

In vanilla JavaScript, you can use a whole bunch of different strategies to navigate your way through this hierarchy. Some of the power of React lies in its ability to handle that navigation for you, maximizing efficiency by deciding to render or re-render parts of the web page only when necessary.

To do that, React needs a way to connect the component you’re programming to the actual element that gets rendered as part of the web page. That’s what the key is for — it’s a unique identifier that React can use to keep track of which elements it should re-render when. If you don’t provide a key, you get the warning above.

Since this problem usually shows up when you’re iterating over an array anyway, it might seem like a simple solution would be to use the index of the array as the key.

Do not do this.

The main danger here is that if you change the order of the elements in the array, the key will no longer match the part of the web page React originally connected it to, and you’ll get all kinds of weird errors. Sure, this strategy can technically work if you’re not changing the array, but it’s a bad habit to get into. Just don’t do it.

A much better solution is to generate a unique string of characters to use as the key.

Enter uuid, an npm library designed to solve this exact problem.

Just run npm install uuid in the terminal to get started. Then, in the file where you want to generate the keys, add the following import:

import { v4 as uuid } from ‘uuid’;

In the component where you need the key, add the following prop: key={uuid()}. That will call a function that generates a unique string of characters for you.

And that’s it — problem solved!

--

--

Alyssa Lerner First
Alyssa Lerner First

Written by Alyssa Lerner First

Software developer and science/tech writer. Python, Ruby on Rails, JavaScript, React/Redux, Java. Fascinated by the amazing stories behind today’s tech.

No responses yet