Using Keys in React

I recently started working on a mobile website that uses React for its view part. One thing I found to be critical was the usage of key.

Consider the below render function

render() {
const dataArray = [
 { id: 1, value: 'First' },
 { id: 2, value: 'Second' },
 { id: 3, value: 'Three' }
return (<ul> { => <li>{data.value}</li>) } </ul>)}

When you will run it, the list is displayed but with a warning from React

As the warning says, Each child in an array or iterator should have a unique key prop, it becomes clear that anything that is inside a map function must have a prop by name key with an unique value.


A person who is new to react may be intimidated to use Math.random to solve this and updates his code to => <li key={Math.random()}>{data.value}</li>)

Run it now and you will se no warnings or errors in console. However this is what React has to say about using Math.random()

Keys should be stable, predictable, and unique. Unstable keys (like those produced by Math.random()) will cause many component instances and DOM nodes to be unnecessarily recreated, which can cause performance degradation and lost state in child components.

Values produced by Math.random() are definitely not predictable and in each render they will generate new value.


You will then try to fallback on something that will be predictable. Since we are inside an iterator function, using an index as a key will be a good idea. So our code now becomes, index) => <li key={index}>{data.value}</li>)

But using index as key is an anti-pattern. A key is the only thing React uses to identify DOM elements. What happens if you push an item to the list or remove something in the middle? If the key is same as before React assumes that the DOM element represents the same component as before. However that is no longer true.

So what should be used ultimately ?


Yes an id. In most of the cases, the data that you are going to render from the server must be having some unique field that differentiates each item in its collection. In our case it’s an id. So if you add/remove an item, React will have no problem., index) => <li key={}>{data.value}</li>)

or if you want to modify key value for debugging purpose

key={`${} - ${data.value}}

The above is just a quick read or you can say it’s the tip of the iceberg, if you want to dive deep, below are good reads.

Happy Coding !!

Originally published at on May 14, 2017.

One clap, two clap, three clap, forty?

By clapping more or less, you can signal to us which stories really stand out.