list and keys

what is Lists & Keys in React ?

  • Profile picture of Mcs
  • by Mcs July 3, 2025

In React, lists are used to display multiple elements dynamically (like items, users, products). When rendering lists, you must use keys to help React track and update the DOM efficiently.

1. Rendering Lists in React

You commonly use the .map() method to loop through an array and render JSX:

Example: Simple List

function App() {
 const cities = ['Mumbai', 'Delhi', 'Pune'];

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

2. What is a Key in React?

A key is a special string attribute you must include when creating lists.

Why keys?

  1. Help React identify which items changed, added, or removed
  2. Make list updates faster and more efficient
  3. Avoids unnecessary re-renders

Example: List of Objects with Unique Keys

function UserList() {
 const users = [
   { id: 1, name: 'Jigar' },
   { id: 2, name: 'Ami' },
   { id: 3, name: 'Ravi' }
 ];

 return (
   <ul>
     {users.map(user => (
       <li key={user.id}>{user.name}</li> //  Use unique ID as key
     ))}
   </ul>
 );
}

Why Not Use index as Key Always?

Using index as key is okay only when:
  1. Items don’t have a unique ID
  2. List won’t be reordered, filtered, or updated

Otherwise, it can cause bugs (like incorrect item highlighting or unexpected animations).

Best Practices for Keys

DOsDON'Ts
Use unique IDs if availableDon’t use index unless necessary
Add key at topmost JSX elementAvoid duplicate keys
Keep key stable across rendersDon’t generate new keys every time

Summary

ConceptDescription
listRendered using .map()
keyUnique identifier for each list item
PurposeHelps React update UI efficiently

Comments

Add new comment

Restricted HTML

  • Allowed HTML tags: <br> <p> <h2 id> <h3 id> <h4 id> <h5 id> <h6 id> <cite> <dl> <dt> <dd> <a hreflang href> <blockquote cite> <ul type> <ol type start> <strong> <em> <code> <li>
  • Lines and paragraphs break automatically.
  • Web page addresses and email addresses turn into links automatically.