REACT Lists and Keys

Sneha Mallik
Last Updated: May 13, 2022

Introduction 

React lists and keys are among the most basic concepts. This may be the most troubling step for beginners who are just getting started with the React framework. What's scarier is that you can't avoid using lists because practically every application has repetitive content.

 

But, in practical terms, react lists and keys are pretty simple. All that is required is for it to be conveyed properly. Lists are an essential element for any application. Lists are used in almost every application in some way or another. You may have a task list similar to a calendar app, a photo list similar to Instagram, a shopping cart list, and so on. There are several applications. Lists in an application might be resource-intensive. Imagine an app with a vast list of videos or photos, and as you scroll, you keep getting hundreds more. This could have a negative impact on the app's performance.

Because performance is crucial, you should ensure that any lists you use are built to be as efficient as possible.

 

Did you know that when using lists in React, each list item needs its own unique key? Let's learn more about React lists and keys, as well as how to use them correctly.

React Lists

Almost every project I've ever worked on included a list of elements. React also makes it a lot easier to render lists in JSX by supporting the Javascript .map() technique.

In Javascript, the .map() method iterates through the parent array, calling a function on each element. Then it creates a new array containing the values that have been changed. It does not affect the parent array.

React Keys

One more thing is required when establishing a list of elements, and that is a key.

The element's key is a specific property that must be included in the element, and it must be a string. Each list's key should be distinct, which means you shouldn't use values that are identical to the key. 

Each item within an array must have a unique key, but the key need not be globally unique. The same key can be used across various unrelated components and lists. To put it differently, keys should be unique among siblings rather than globally.

For example, you should not use status or text as a key because they are not identifiers.

The element's key serves as a form of identifier for React, allowing it to figure out which element was updated, added, or removed.

It's a good idea to pick a value that serves as a unique identifier for each item in the array, which is usually the ID.

Creating a basic List component

Lists are commonly used to show lists on websites and are used to display data in an ordered way. Lists can be generated in React in the same way that they are in JavaScript. Let's look at how Lists are transformed in regular JavaScript.

The traversal of lists is done with the map() function.

function ListComponent(props) {
    const listItems = myList.map((item) =>
    <li>{item}</li>
    ); 
    return (
    <ul>{listItems}</ul>
    );
}

const myList = ["Lotus", "Rose", "Sunflower", "Marigold", "Lily"];
ReactDOM.render(
    <ListComponent myList={myList} />, 
    document.getElementById('root')
);

 

The code above shows a ListComponent that renders a list of props provided to it. We called the ListComponent in the render() method and handed it a list called myList as props. The following is the outcome of this code:

Lotus
Rose
Sunflower
Marigold
Lily

 

When you run this code, we'll notice that React issues a warning.

"Warning: Each child in an array or iterator should have a unique 'key' prop.%s%s See https://fb.me/react-warning-keys for further information.%s"

 

It's important to note that the caution here is about providing a unique key. Let us know how to use keys to increase the performance of your React application.

Use of React keys in React Lists

React uses keys to figure out which elements have changed (added, removed, or re-ordered). A key is necessary to give each element in the array a unique identity.

Let's rewrite the React code sample we saw previously in React lists to incorporate keys to better comprehend this.

function ListComponent(props) {
    const listItems = myList.map((item) =>
    <li key={item.id}>
        {item.value}
    </li>
    );
    return (
    <ul>{listItems}</ul>
    );
}

const myList = [{id: 'a', value: ‘Lotus’},
              {id: 'b', value: ‘Rose’},
              {id: 'c', value: ‘Sunflower’},
              {id: 'd', value: ‘Marigold’},
              {id: 'e', value: ‘Lily’}];
ReactDOM.render(
    <ListComponent myList={myList} />,
    document.getElementById('root')
);

 

The key in this method is a one-of-a-kind string that identifies each item. Note that we've included a key for each list item in this code snippet above. Also, note that the original React list has been changed to be a value-id pair. A unique id is assigned to each item in the array. As a result, this is the id that is allocated to each object as a key. This is the most effective method for assigning unique keys to items on a list.

Is it better to use the index as a key in your project or not?

There are three conditions you must check, and they must all be met in order for you to utilize index as a key in your list with confidence:

  • The list is never sorted or filtered.
  • On the list or list items, you never make any changes or computations.
  • The list's items have no identifiers(id).

 

Note: Using an index as a key may cause the component to behave in an unexpected way. The order of items may change, hence utilizing indexes as keys are not recommended. This can have a negative impact on performance and cause component state difficulties.  If you don't set an explicit key to a list item, React will use indexes as the default key.

Extracting Components with keys

Consider the following scenario: we've constructed a separate component for list items, and we're extracting list items from it. We'll have to assign keys to the component we are returning from the iterator rather than the list elements in that case. That means, instead of assigning keys to <li>, we should assign them to <Component />. To avoid making a mistake, remember that anything we return from the map() function must be assigned a key.

Keys make sense only in the context of the surrounding array. 

For example, if you're extracting a ListItem component, you should preserve the key on the array's <ListItem /> elements rather than the <li> element in the ListItem itself.

Great, now that we know a lot about keys, let's look at how we can generate unique keys if you don't already have them in your data.

Generate unique React keys

Let's say the data you're working with doesn't include any unique values, such as ids or other identifiers, and you really need to utilize something other than the index value. If that's the case, there are at least two options.

  • Create the key on your own.

A simple Javascript code can be written to generate a random integer or string. To produce a random integer, you can also use a new Date().getTime() Javascript methods, add any prefix and use it as your key.

 

  • Make use of a plugin that already exists.

For generating unique keys for React lists, there are a few options. The shortid ‘generate()’ technique is one that we can use but since this is deprecated we can use nanoid instead. ‘uuid’ and ‘uniqid’ are two others that come highly recommended. They're all really straightforward to set up and operate. 

Nanoid is highly recommended as it is 2 times faster than ‘uuid’, safe, secure, URL-friendly, and is a unique string ID generator for Javascript. 

 

These methods will solve almost all the problems with React lists and keys.

A "key" prop should be assigned to each child in a list

The final point to make in this article concerns the most typical and persistent mistake you'll encounter in the console when developing.

If you encounter the following error ‘Each child in a list should have a unique key prop…’, you already know that the only option is to give each of your list items a unique key.

Even if you've already allocated the key, the issue could indicate that one of the keys isn't unique. To overcome this, you must use one of the above-mentioned ways in “Generate unique React Keys” to ensure that your key value is unique.

Frequently Asked Questions

  1. What is the use of React Lists?

Lists are generally used to present data menus on websites and are used to display content in an ordered way. Lists can be generated in React in the same way that they are in JavaScript. The traversal of lists is done with the map() function.

 

2. What do you mean by React Keys?

The React key is a unique identifier. It's used in React to figure out which items in the Lists have changed, been updated, or been removed. It's beneficial when we've added components dynamically or when users change the lists. It also assists in determining which components in a collection need to be re-rendered rather than rendering the complete collection each time.

To provide the elements a stable identity, keys should be given inside the array.

 

3. Are React keys and props the same thing?

The keys and props are not the same thing; the process of assigning "key" to a component is the same. Keys are internal to React and, unlike props, cannot be accessed from within the component. As a result, we would need to pass the key as another prop.

Key Takeaways

In this blog, we went over the fundamentals of React lists and keys. We also learned how to create a list in React JSX and what keys are, and why they're important to include.

We also learned about the many ways for creating unique ids and why key uniqueness is critical in some instances. Let's review the main points of this article of react lists and keys.

  • Lists are resource-intensive and should be utilized with caution.
  • Make sure that each and every item in the list has its own key.
  • It is preferable not to utilize indexes as a key unless you are certain that the list is static (no additions, reordering, or removals).
  • To generate a key, never use insecure keys like Math.random().
  • If unstable keys are utilized, React will experience performance degradation and unexpected behavior.

 

Enroll in our Advance Front-end Web Development Course- React.js to deeply understand the concept of React lists and keys in Web Development. 

Credits: GIPHY

 

Happy Developing!

Was this article helpful ?
0 upvotes