SmartCodingTips

🔑 Keys in Lists

Keys help React efficiently update and re-render list items by identifying which items have changed, been added, or removed.


📌 Why Are Keys Important?

  • They allow React to identify list items uniquely.
  • Improve rendering performance and prevent UI bugs.
  • Are required when rendering dynamic lists using .map().

✅ Using Unique Keys


const users = [
  { id: 1, name: "Alice" },
  { id: 2, name: "Bob" }
];

function UserList() {
  return (
    <ul>
      {users.map((user) => (
        <li key={user.id}>{user.name}</li>
      ))}
    </ul>
  );
}

🚫 Avoid Using Index as Key

Keys should be stable and unique. Using the array index may lead to unexpected behavior when the list is modified.


// ❌ Not recommended
{items.map((item, index) => (
  <li key={index}>{item}</li>
))}

// ✅ Better
{items.map((item) => (
  <li key={item.id}>{item.name}</li>
))}

💡 Best Practices

  • Use unique IDs when available (like database IDs).
  • Don't use array indexes unless the list is static and never changes.
  • Keep keys consistent between renders to avoid reordering issues.

📋 Summary

  • Keys are crucial for rendering lists efficiently in React.
  • Use stable, unique values as keys.
  • Avoid using indexes unless there's no alternative.