REACT Tutorial



LIST & KEYS IN REACT


List and Keys in React

Rendering lists of data efficiently is a core part of React. React lets you loop through arrays and display elements using the map() method. Each item in a list requires a unique key attribute to help React identify which items have changed, added, or removed.

Rendering a List with map()

You can create an array of elements by transforming an array of data. Here’s a simple example rendering a list of fruits:

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

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

Why Keys are Important?

Keys help React track which items have changed, so it can efficiently update the UI without re-rendering the entire list. A good key is:

  • Unique across the list
  • Stable (doesn't change over time)
  • Preferably not using array indices unless the list is static

Using Unique IDs as Keys

If your data items have unique IDs, use those as keys instead of indices:

const todos = [
  { id: 1, text: 'Learn React' },
  { id: 2, text: 'Build Projects' },
  { id: 3, text: 'Get Job' }
];

function TodoList() {
  return (
    <ul>
      {todos.map(todo => (
        <li key={todo.id}>{todo.text}</li>
      ))}
    </ul>
  );
}
  
Try this yourself: Render a list of your favorite movies or books using keys!

🌟 Enjoyed Learning with Us?

Help others discover Technorank Learning by sharing your honest experience.
Your support inspires us to keep building!

Leave a Google Review