Prevent usage of Array index in keys – React

React

So, React has thrown you a curveball – or, you’ve discovered when linting your getting a warning saying “Prevent usage of Array index in keys”. Huh? Well, you probably already know the issue, but let’s delve into it – and how to fix it.

What’s the issue?

React requires a unique key prop for every item that you place into a list. Why? It uses this to update the UI and track changes to the item. So far so good.

The problem comes when array indexes are used for these key props. Initially rendered, all is fine. But as soon as you start moving items around, adding new ones or even deleting items the problem should become clear.

The list that started out like:

1
2
3
4
5
6

after some changing is now:

6
2
4
2

And there’s our ‘Houston, we have a problem’ moment!

We can end up with a whole range of difficulties including the list being rendered out of order (after all, React could incorrectly presume that the order of these items is going to remain constant – in some lists this won’t be a problem. But if it’s editable in any way then we’re doomed.

It can also lead onto poor performance as React tries to keep track of everything that’s changing in the list when you’re moving the items around, creating new ones or binning them off altogether.

And whilst we’re on the subject of re-ordering – React might create and destroy components unnecessarily affecting their state, elongating load times and making bugs a pain in the behind to track down – or even causing bugs themselves.

So, let’s fix it – it’s really easy.

The Solution

It’s simple really – give your key props a meaningful name that is NOT an array index.

You could set up a function to generate a random name of course – which will clear the warning – but may make the whole debugging process a lot more fun!

You’ve got a few options:

Use a unique identifier – if you’re loading data from a database, great! You already have a primary key. Throw this into the key prop instead. As the primary key of the database row will never change, nor will your key prop.

Utilise a third party library to generate random ID’s for you. UUID or ShortID can be used for this purpose.

Use your data as the key – throw in the entire text property if you’re feeling brave – just make sure it is actually unique!

Create a key by mashing some of the data together – for example the name of the object (e.g. customer) and an ID.

Essentially, using anything other than the blasted array index that is unique to that component will work and get rid of your “Prevent usage of Array index in keys” forever!

Happy Reacting!

You may also like...

0 0 votes
Article Rating
Subscribe
Notify of
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x