Flat Preloader Icon

Lists and Keys

In React, lists and keys are fundamental concepts for rendering collections of data and efficiently updating the UI. Here’s an introduction to how you can work with lists and keys in React:

Rendering Lists

React makes it easy to render lists of data. Typically, you’ll map over an array of data and return a list of React elements.
				
					import React from 'react';

const NumberList = () => {
  const numbers = [1, 2, 3, 4, 5];
  return (
    <ul>
      {numbers.map(number => (
        <li key={number}>{number}</li>
      ))}
    </ul>
  );
};

export default NumberList;

				
			

In this example:

  • The numbers array contains the data we want to display.
  • We use the map function to iterate over the array and return a <li> element for each item.
  • The key attribute is assigned to each list item to help React identify which items have changed, are added, or are removed.

Keys in React

Keys are a special attribute you need to include when creating lists of elements. Keys help React identify which items have changed, been added, or been removed. They should be given to the elements inside the array to give the elements a stable identity.

Why Keys Are Important

Keys help React optimize the rendering of lists. Without keys, React would have to re-render all items every time there’s a change. With keys, React can update only the changed items, improving performance.
  • Lists: Use the ‘map’ function to render lists of elements from an array.

  • Keys: Assign a ‘key’ attribute to each element in the list to help React efficiently update the UI.