Logo

Developer learning path

React

Keys in React

Keys

45

#description

In React, Keys are used to identify unique items (or elements) in an array that is being rendered in some UI component. Whenever we render such an array (using map() function, for example) using React’s JSX syntax, React requires us to provide a unique key for each item in the array. This key helps React identify which items have been added or removed from the array, so that it can update the UI (the virtual DOM) efficiently.

Why are keys important in React?

In modern web applications, it is very common to render dynamic data in Lists or Tables, where we may need to add or remove items from the list at runtime. In React, we can do this by simply updating the state of the Component that contains the list, and React will automatically re-render the list UI based on the new state data.

However, when rendering Lists or Tables, we also need to ensure that the UI effectively represents the state of the data that it is displaying. That is why keys are important - they help React efficiently update the UI while keeping it in sync with the underlying data.

If we do not provide keys to JSX elements, React will warn us with a message saying that a “key” prop is missing on the list items.

Here is an example of how to use keys in React:

                    
const myArray = ['apple', 'banana', 'orange'];

const myList = myArray.map((item, index) => (
  <li key={index}>{item}</li>
));

return (
  <ul>
    {myList}
  </ul>
);
                  

In this example, we create an array of fruits and then use the map() function to generate a list of list items (

  • ) from the array. We provide the unique key prop by using the index of each item as the key value.

  • March 25, 2023

    If you don't quite understand a paragraph in the lecture, just click on it and you can ask questions about it.

    If you don't understand the whole question, click on the buttons below to get a new version of the explanation, practical examples, or to critique the question itself.