Why the key prop is necessary in React?

Hi, in this post I’m going to explain why React need a key prop to work and we are going to look that if we don’t insert the “key” then we are going to have a warning in the console.

In this code: we have a list of items ketchup, mustard, salsa and oil and every element have a button to remove that element also we have one general button to add a new item to the list.

// Dependencies
import React, {useState} from 'react'

// Array with all the items
const allItems = [
  {id: 'ketchup', value: 'ketchup'},
  {id: 'mustard', value: 'mustard'},
  {id: 'salsa', value: 'salsa'},
  {id: 'oil', value: 'oil'},

// Component
function App() {
  // Local state
  const [items, setItems] = useState(allItems)

  // Method to add Item
  const addItem = () => {
    const itemIds = items.map(i => i.id)
    setItems([...items, allItems.find(i => !itemIds.includes(i.id))])

  // Method to remove item
  const removeItem = item => {
    setItems(items.filter(i => i.id !== item.id))

  // HTML render
  return (
    <div className="keys">
      <button disabled={items.length >= allItems.length} onClick={addItem}>
        add item
      <ul style={{listStyle: 'none', paddingLeft: 0}}>
        {items.map(item => (
            <button onClick={() => removeItem(item)}>remove</button>{' '}
            <label htmlFor={`${item.id}-input`}>{item.value}</label>{' '}
            <input id={`${item.id}-input`} defaultValue={item.value} />

export default App

View: list of items ketchup, mustard, salsa and oil and every element have a button to remove that element also we have one general button to add a new item to the list.

Ok, with this code we are going to see our browser console and we are going to have this warning message from React:

index.js:1 Warning: Each child in a list should have a unique “key” prop

And is ok, if we look in Google how to fix this the answer will be – ok insert a unique key value in the key prop like this:

And yes! that is the perfect solution to remove the warning, but why? why we need to use this key prop?

Ok, in the original code (without inserting the key code) if we remove an item then we are going to see weird behaviors in the input values, so lets remove “ketchup

Then the list will be updated and look how the “ketchup” value is moving with mustard instead of be deleted also the other remaining items are incorrectly associated:

That’s the issue – so every time that we click on “remove” button React is rendering the App component again with the “items” (that also have one less item that was before).

The way that React update the DOM is that has a reference to JSX elements that we give it the last time that we render this App component then React compare those elements with the new elements that just returning this time and then updated the DOM accordingly.

So when we given it a array of elements unless React have some sort of identified to know which element is which React doesn’t know whether you remove an element or maybe you add a third element and remove the four element in that case React does not have any insight into what we did to this array of elements between the last time was rendered and the new time.

So anytime that we render an array of elements we need to give it a unique key so in that way React can determine whether elements were removed, added or modified, so that’s why when we insert a unique key the React warning despair.

Now with this fix – if we remove items from the list then all the inputs will be correct:

Note: The key need to be unique for every element, so that’s mean that this is NOT correct key=’list-item’

Note: is a mistake use the .map index as key={index} because React is comparing the previous version with the new version saying that the element that was added at index 4 is actually now at index 3 but React doesn’t know that.

By Cristina Rojas.