The Importance of Keys in React
How many times have you been trying to render a list and you get this error? What does it really mean?
What are Keys?
Keys help React identify which items have changed, are added, or are removed. Keys should be given to the elements inside the array to give the elements a stable identity — React Docs
First, we need to understand that keys are for identification and not directly for performance. Keys will impact performance due to how React uses them for DOM updates.
Keys do not need to be globally unique. They just need to be unique among their siblings within the same array.
Can we just use the array index?
In short, no.
We don’t recommend using indexes for keys if the order of items may change. This can negatively impact performance and may cause issues with component state. […] If you choose not to assign an explicit key to list items then React will default to using indexes as keys. — React Docs
Process React takes when removing an item from the array:
- Remove the item with the key
- Update the array (Changing the ids for all of the items in the list after the grape object)
- Re-render the rest of the array since the ids all updated
Even after re-adding the grape back into the array, the pear input is still messed up. This is what happens if you use the index as the key.
The Solution
The solution is to simply pick a key that will be unique among the other siblings in the array. Most commonly, an item will have an id
that can be used as the key. This will make it easier for React to identify the correct item that is being added/removed from the array and not update the incorrect items.
Another option would be to generate a unique id by using an external library. It is NOT recommended to use Math.random()
as that will generate a new id every time the component is updated. This would defeat the purpose of using a key as identification.
What if I’m rendering components?
React thought of this too. You do NOT put the key within the components’ <li>
but instead on the component itself.
RULE OF THUMB: The elements inside of the map()
calls need keys