List and Keys in React

1. Lists in React

A list is typically an array of items that you want to display in the UI. In React, you often use the .map() method to render these arrays into components or JSX elements.

Example:

import React from "react";

function FruitList() {
  const fruits = ["Apple", "Banana", "Cherry"];

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

export default FruitList;

✅ Here:

  • fruits is an array.
  • We use .map() to iterate over it.
  • Each fruit becomes an <li> element.

2. Keys in React

React needs a unique identifier for each element in a list to efficiently update and re-render only the changed items. This unique identifier is called a key.

Without keys, React may re-render the whole list unnecessarily, causing performance issues or bugs.

Example with keys:

import React from "react";

function FruitList() {
  const fruits = ["Apple", "Banana", "Cherry"];

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

export default FruitList;

✅ Here:

  • key={index} gives each <li> a unique identifier.
  • Best practice: Use a unique ID if available instead of the index, especially if the list can change dynamically.

Example with unique IDs

import React from "react";

function FruitList() {
  const fruits = [
    { id: 1, name: "Apple" },
    { id: 2, name: "Banana" },
    { id: 3, name: "Cherry" },
  ];

  return (
    <ul>
      {fruits.map((fruit) => (
        <li key={fruit.id}>{fruit.name}</li>
      ))}
    </ul>
  );
}

export default FruitList;

✅ Advantages:

  • React can track which items are added, removed, or changed.
  • Avoids unnecessary re-renders.
  • Prevents bugs when the list updates dynamically.

In short:

TermMeaning
ListAn array of items rendered in JSX, usually via .map().
KeyA unique identifier for each item in the list to help React manage updates efficiently.

Leave a Reply