Understanding React keys

If you use React you need to understand keys.

Key concept

In React, keys are the guiding beacon.

A react key is an attribute, you can add it like that:

<ul>
{myPosts.map(({post}) => (
    <li key={post.slug}><a href={post.url}>{post.title}</a></li>
))}
</ul>

Source

The classic warning

Warning: Each child in an array or iterator should have a unique « key »

It’s easy to make that warning disappear but some solutions are not recommended.

Bad solutions

The following approaches are pretty bad. I will explain why. Please do not use them.

randomize

Easy but counterproductive.

Look at the following (I’ve seen it before…):

<li key={randomize()}>... etc

randomize() is not smart at all! It will trigger a re-render every time.

This may lead to bad overall performances!

It’s an anti-pattern to React because of the very nature of its algorithm.

Using indexes

It’s not so rare to see this too. People like to use array indexes as keys, so 0,1,2,3,4…n, where n is the number of iterations :

{myData.map((data, index) =>
  <MyComponent {...data} key={index} />
)}

It might work and it’s better than using randomize() but if you have complex structures like arrays of arrays, this will fail.

What are the keys?

React use keys to detect changes. This way, it knows if something has been added, changed or deleted.

But why?

This way its actions on DOM are optimized.

Good practices

Whenever the word « good practices » is pronounced you have to be wary but anyway, keys are identifiers.

Just look at the following :

<ul>
{myPosts.map(({post}) => (
    <li key={post.id}><a href={post.url}>{post.title}</a></li>
))}
</ul>

I’m using key={post.id}, I could use key={post.slug} too. The idea is to use something very unique and stable.

For example, [ page.lang ].date with format Y-m-d would be stupid here.

Why must the keys be stable and unique?

React relies on a comparison algorithm. It compares 2 sets of keys. This way, it knows critical differences and it’s easier to create, update, or delete things.

Source

That’s pretty much the reason why keys must be stable and unique. Without it, React would recreate everything all the time.

No zeal please

Some solutions are bad and some are useless. The following makes no sense:

render() {
    return (
        <MyComponent key="theGreatEscape" />
   );
}

React does not care. It’s possible to use libraries to generate keys but please make sure they are static.

Wrap up

Yes you MUST fix the warning: « Warning: Each child in an array or iterator should have a unique key ». Otherwise, React will re-render everything all the time!

Learning keys is a nice way to get a deeper knowledge of React.