Better Programming

Advice for programmers.

Follow publication

Member-only story

3 Common Mistakes With React Keys

Tyler Hawkins
Better Programming
Published in
4 min readSep 4, 2020
Photo by Jason D on Unsplash

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:

Create an account to read the full story.

The author made this story available to Medium members only.
If you’re new to Medium, create a new account to read this story on us.

Or, continue in mobile web

Already have an account? Sign in

Tyler Hawkins
Tyler Hawkins

Written by Tyler Hawkins

Staff software engineer. Continuous learner. Educator. http://tylerhawkins.info