So, what is the key prop?

So, what is the key prop?

It would be fair to assume that almost every developer has had a console warning of not providing a key prop when a list was rendered in a React application. To fix this, you pass the key prop and sometimes use the index as the value. But why do you need the key? What is the key prop? Is using the index parameter a good practice? This article will explain the key prop and its impact on the performance of your application.

The key prop

The key prop is an identifier that React uses to keep track of items being added, modified or removed from the DOM. It is added as an attribute to elements that are rendering list items.

Applying the key prop in React lists

function Key() {
  const skills = ["Javascript", "React", "Vue", "SQL"];
  return (
     <ul>
        {skills.map((skill) => (
          <li>{skill}</li>
        ))}
      </ul>
 );
}

export default Key;

In the above code, an array of skills is being mapped and rendering this in the browser will trigger a warning in the console, asking for a key prop.

To resolve this warning, the skill being returned from the .map() method can be passed as the key prop:

function Key() {
  const skills = ["Javascript", "React", "Vue", "SQL"];
  return (
     <ul>
        {skills.map((skill) => (
          <li key={skill}>{skill}</li>
        ))}
      </ul>
 );
}
export default Key;

If I were to modify the array by adding the same skill twice,

const skills = ["Javascript", "React", "Vue", "Javascript", "SQL"];

There would be a warning in the console shown below:

Since the skill is being used as the key prop, these two items now have the same key. The duplicated item may be rendered twice, or one of the duplicated items might be omitted. To prevent this from happening, siblings in a list must have unique IDs.

Sources of IDs for key

To generate a unique ID for your items, there are several approaches you can try. These are two of the most common methods below:

  • Universally Unique Identifier (UUID): This is a library used to generate unique IDs. Below is an example of a React application using the react-uuid library

    1. Install the package in your project by running this command:

       npm i react-uuid
      
    2. You can then use it in your project like this:

       import uuid from 'react-uuid';
       function Key() {
         const skills = ["Javascript", "React", "Vue", "SQL"];
         return (
            <ul>
               {skills.map((skill) => (
                 <li key={uuid()}>{skill}</li>
               ))}
             </ul>
        );
       }
       export default Key;
      
  • Database IDs: If you are interacting with a database in your application, you can use the IDs assigned to the data by the database.

Pitfalls of theindex parameter as a prop

To better understand this, let us take an example using the skills array mentioned earlier:

 {skills.map((skill) => (
   <li key={index}>{skill}</li>
 ))}

Our rendered list would look like this:

<ul>
  <li key="0">Javascript</li>
  <li key="1">React</li>
  <li key="2">Vue</li>
  <li key="3">SQL</li>
</ul>;

If I add a new item to the array of skills;

 const skills = ["CSS","Javascript", "React", "Vue", "SQL"];

The rendered list then looks like this:

<ul>
    <li key="0">CSS</li>
    <li key="1">Javascript</li>
    <li key="2">React</li>
    <li key="3">Vue</li>
    <li key="0">SQL</li>
 </ul>;

You will notice that the keys for the items have changed. Using the index as a key does not maintain consistency across re-renders and can lead to problems when a list is being dynamically re-ordered or sorted.

A Practical Example of using index

To demonstrate the problems you might encounter when using index it as a prop, I created a simple to-do app, which you can interact with the sandbox.

Screenshot of the todo app's user interface

The image above is the screenshot of the app. The app allows you to enter new to-do items and sort them by their creation date.

You can try to interact with the application. I would do a demonstration below:

  1. Let us start by adding a new to-do. You can choose to add as many as you like. When you add new to-do items, the index and the ID for each item is displayed. The index is generated based on the position of the item in the list while the ID is based on the current number of items. Here is how the app looks after adding to-do items:

  2. Next, click on the Sort by Latest button. By clicking this button, the list is sorted in a descending manner based on the time they were created. You will notice that the IDs remain consistent with the items but the index does not. This is one of the problems with index.

  3. I'll add a new to-do item to the sorted list. As the new item is added, the ID identifies the new item correctly. However, the index adds the item by its position in the array, which may not be by its position on the sorted list. Here is a screenshot below:

This example highlights the problems with using the index parameter. It shows the importance of using unique and consistent keys when managing lists.

Although it is recommended not to use index as a key in your applications, there are some scenarios when it would not pose a problem in your application. These exceptions are;

  1. If your list is static and is guaranteed to remain the same for a while.

  2. When your list is never going to be re-ordered or filtered.

Performance impact of key prop.

The importance of the key prop in optimizing the performance of your application when rendering lists is paramount. If used correctly, React can efficiently reconcile the virtual DOM with the actual DOM. This reconciliation process involves rendering items in a list based on if they have been modified, or removed since the previous render.

For instance, if a social media network application has a million users and renders a list of user comments without correctly using the key prop, it would lead to the app lagging which could result in a poor user experience. The reason is without providing a key prop, if a user edits or adds a new comment, React re-renders the entire list of user comments.

Conclusion

The key prop is essential in React applications. Even though it is an identifier used to keep track of items in a list, its importance in the performance optimization of your application is essential. I hope with this article you have fully grasped the concept of the key prop and you know the dos and don'ts while passing a value to the prop.