DEV Community

Gary Menzel
Gary Menzel

Posted on

Thoughts about "keys" on React lists

It's been a while... a LONG while....

This is a really short post about the key property on React components that are lists (i.e. arrays)...

I really like to get rid of all the React warnings about unique keys on lists. You really want everything to have a unique key when it is part of a list so that things update reliably.

But when you get the warnings sometimes it can be difficult to work out which component in which list is the offender.

What I have found useful is to search anywhere you are using iterators (like map or reduce) and make sure you are composing a unique key on any component the iterator might return.

The other place to look is for any .push calls that might be creating the array with a component as the thing you are pushing and make sure they have unique keys.

Generally, I compose the key from part of the data and an index from the iterator. If that is not unique enough, then I might also add a prefix or suffix to the key as well.

I like my keys to have a reasonably consistent format to them and separate sections of the key with a dash (hyphen).

Doing this should ensure you have consistent key generation and keep the keys all unique.

Top comments (0)