What is the Key Prop in React?

React ImportantServiceNowSpotifyAmazonMicrosoftLinkedIn

Key Prop in React

The key prop is a special attribute that helps React track and manage elements in a list efficiently. When rendering arrays of elements, keys enable React to determine which items have been modified, inserted, or deleted. Here's a simple example:

const users = [
{ id: 1, name: 'Alice', email: 'alice@example.com' },
{ id: 2, name: 'Bob', email: 'bob@example.com' },
{ id: 3, name: 'Charlie', email: 'charlie@example.com' }
];

const userList = users.map((user) => (
<li key={user.id}>
{user.name} - {user.email}
</li>
));

When choosing a key, it's essential to select a unique identifier that distinguishes each item within its list. In real applications, you'll typically want to use unique identifiers from your data, such as database IDs. For example:

const users = [
{ id: 1, name: 'Alice', email: 'alice@example.com' },
{ id: 2, name: 'Bob', email: 'bob@example.com' },
{ id: 3, name: 'Charlie', email: 'charlie@example.com' }
];

const userList = users.map((user) => (
<li key={user.id}>
{user.name} - {user.email}
</li>
));

In this example, we use user.id as the key because it's a unique identifier for each user, making it perfect for React's reconciliation process.

Common Pitfall: Using Array Index as Key

While it might be tempting to use the array index as a key, this is generally a bad practice:

// ❌ Bad practice: using index as key
const userList = users.map((user, index) => (
<li key={index}>
{user.name} - {user.email}
</li>
));

// ✅ Good practice: using unique ID as key
const userList = users.map((user) => (
<li key={user.id}>
{user.name} - {user.email}
</li>
));

Using array indices as keys can lead to:

  • Performance issues when the list order changes
  • Bugs with component state when items are inserted or deleted
  • Problems with list item animations

The only time it's acceptable to use the index as a key is when all of these conditions are met:

  • The list is static (not computed and doesn't change)
  • The items in the list have no IDs
  • The list will never be reordered or filtered
00:00