Using indexes as keys is more dangerous than what you think it is

If you watched a video talking about rendering lists in react, you most likely have heard them saying that it's not recommended to use indexes for keys in dynamic lists.

The main reason that you usually will hear is: It badly affects the performance because it may cause React to un-necessarily re-render some of the children that didn't change.

Which is totally true. But some extra re-renders doesn't honestly sound that bad to you, does it??

And because of that, you may sometimes feel like ignoring this rule & just using indexes because it's easier. (We programmers love laziness 😁)

However...

What you might not know is that, there's a high chance you are creating a bug that will come later to haunt you for hours...

But why is that?? you ask.

It's because aside from performance, using indexes as keys WILL cause React to incorrectly associate some internal things with the wrong component. And by "internal things" I mean things like:

  • html input's value
  • useRef value
  • running useEffect

Sounds dangerous to you yet??

If not, just imagine that you are building a shopping cart page where you show a list of selected items, and each item has a "items count" input. And you are using indexes as keys for the cart items. Now what will happen if the user removes an item from the cart? The item that was below it will now have the removed item's "Count" value!!

This means that the user will receive & pay for an order different than what he actually ordered! And that's catastrophic...

& you know what the worst part is?? This kind of bugs is usually hard to find & it doesn't happen all the times, so you might miss it on development, but then receive random feedback saying that something is broken but you can't figure how or why.

So really, just save yourself a lot of trouble later & never use indexes for lists that are dynamic or can be re-ordered.

And that's it for this time folks.

Until next time & have a great day 👋

My Photo

About Me

I'm a freelance web developer who specializes in frontend.
I have a special love for React. And my personal goal is: Building things that are Awesome! ✨
If you are someone who is building a project where high quality is a MUST, then Let's Chat! I'll be glad to help you with it.

© 2023-present Mohammed Taher Ghazal. All Rights Reserved.