D Dev Notebook

React Lists & Keys

Lists and Keys are essential concepts when rendering multiple elements dynamically from an array.

A list in React is a way to display multiple similar items (like text, images, or components) by looping over an array using .map(). It allows dynamic and scalable rendering of UI elements.

const fruits = ['Apple', 'Banana', 'Cherry'];

function FruitList() {
  return (
    <ul>
      {fruits.map(fruit => <li>{fruit}</li>)}
    </ul>
  );
}

React Keys

Keys help React identify which items have changed, are added, or are removed. This improves performance and avoids bugs during re-rendering.

Why are keys important?

  • They help React maintain the correct order and identity of elements.
  • Without keys, React re-renders all items, even if only one changes.
const fruits = ['Apple', 'Banana', 'Cherry'];

function FruitList() {
  return (
    <ul>
      {fruits.map((fruit, index) => (
        <li key={index}>{fruit}</li> 
      ))}
    </ul>
  );
}

important

  • Avoid using array indexes as keys if the list can change (reorder, delete, etc.).
  • Prefer using a unique id if available.
const fruits = [
  { id: 1, name: 'Apple' },
  { id: 2, name: 'Banana' },
  { id: 3, name: 'Cherry' },
];

function FruitList() {
  return (
    <ul>
      {fruits.map(fruit => (
        <li key={fruit.id}>{fruit.name}</li>
      ))}
    </ul>
  );
}
ConceptPurpose
ListDynamically render elements from an array
KeyGive each element a unique identity to optimize updates

Code Snippets

On this page