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.

AWS GenAI LIVE image

How is generative AI increasing efficiency?

Join AWS GenAI LIVE! to find out how gen AI is reshaping productivity, streamlining processes, and driving innovation.

Learn more

Top comments (0)

Billboard image

Create up to 10 Postgres Databases on Neon's free plan.

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Try Neon for Free →

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay