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 Q Developer image

Your AI Code Assistant

Automate your code reviews. Catch bugs before your coworkers. Fix security issues in your code. Built to handle large projects, Amazon Q Developer works alongside you from idea to production code.

Get started free in your IDE

Top comments (0)

Postmark Image

Speedy emails, satisfied customers

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up

👋 Kindness is contagious

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

Okay