Member-only story
3 Common Mistakes With React Keys
The key to working with keys
When first learning React, it’s easy to get tripped up by simple mistakes. Even seasoned developers make mistakes.
One area that is often misunderstood is how to use a key
when iterating over items to be displayed in the UI.
In this article, we’ll look at three mistakes with React keys and how to avoid them.
Why Are Keys Necessary?
First off, let’s make sure we understand why we use keys.
The React docs explain that “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.”
So, keys help identify elements, especially when React is performing its diffing algorithm to note what has changed in the UI.
With that basic understanding in mind, let’s look at our first mistake.
Mistake #1: Not Using a Key
If you are iterating over an array of items, perhaps with the Array.map
helper method, and then displaying those items in the UI, you must add a key to each item.
For example, this shopping list component iterates over an array of grocery items: