I was just wondering while reading article from https://coderwall.com/p/jdybeq/the-importance-of-component-keys-in-react-js.
It has a simple fiddle code which says - If you dont have unique constant keys you might end up in
Its quite confusing in below cased -
Expanding on the @Deadfish answer. Let's say you have 10 todo items, and each item has state (e.g. whether it is in editing mode).
On the next render pass, there are only 9 todo items left. E.g. because you deleted one of the items.
Now react needs to know which of the original 10 items are still left, so it can preserve the state of each item, and re-render only items that changed state.
That is what react uses the key
for. If you use the index as the key, then the original keys were 0..9. And the new keys are 0..8.
This can cause several problems:
Using unique and constant keys - so not just unique in a single render run, but especially constant over multiple render-cycles - will ensure that everything works as intended, and will ensure react updates DOM efficiently.
It is always good to have react keys constant and unique. There will be times when index
will not work well.
Let us consider a scenario where we have two components TodoList
and TodoItem
in our application. The TodoList
component iterates over a todos
array and renders TodoItem
for each todo. Let's say you have opened the second TodoItem
for editing. So it's state says {editing: true}
and it renders an input box instead of Label.
Now if you have used index
as key, then upon deleting the second todo, the third todo will inherit state from the deleted todo and display an input box instead of Label. This happens since they both share same key.
I hope I made myself clear.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With