💡 Learn from AI

React Fundamentals

Lists and Keys

Lists and Keys

In React, rendering lists is a common task when building dynamic user interfaces. Lists can be rendered using a combination of map() and the JSX syntax, but it is important to add a unique identifier to each item in the list to help React optimize the rendering process. This unique identifier is known as a key.

Adding Keys to Lists

Keys help React identify which items have changed, are added, or removed. In the absence of keys, React has to traverse the entire list, which can be slow and inefficient.

Here is an example of rendering a list of items:

const items = ['Item 1', 'Item 2', 'Item 3'];

function List() {
  return (
    <ul>
      {items.map(item => (
        <li key={item}>{item}</li>
      ))}
    </ul>
  );
}

In the example above, we use the map() function to create a new array of list items, and we add the key prop to each list item. In this case, we are using the value of the item as the key.

Best Practices

When adding keys to a list, it's important to use a unique identifier. This could be an ID that is associated with the item or a combination of values that make the item unique.

It's also important to note that keys should be stable, meaning that they should not change between renders. If the key changes, React will treat the item as a new item and create a new component instance, which can be a performance issue.

Further Reading

  • Lists and Keys - React documentation

  • React.js Best Practices for 2021

Take quiz (4 questions)

Previous unit

Conditional Rendering

Next unit

Forms and Controlled Components

All courses were automatically generated using OpenAI's GPT-3. Your feedback helps us improve as we cannot manually review every course. Thank you!