Conceptual Question

What is the Key Prop in React?

React Ecosystem

What is the Key Prop in React?

React

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:

JAVASCRIPT
1const users = [
2 { id: 1, name: 'Alice', email: 'alice@example.com' },
3 { id: 2, name: 'Bob', email: 'bob@example.com' },
4 { id: 3, name: 'Charlie', email: 'charlie@example.com' },
5];
6
7const userList = users.map((user) => (
8 <li key={user.id}>
9 {user.name} - {user.email}
10 </li>
11));

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:

JAVASCRIPT
1const users = [
2 { id: 1, name: 'Alice', email: 'alice@example.com' },
3 { id: 2, name: 'Bob', email: 'bob@example.com' },
4 { id: 3, name: 'Charlie', email: 'charlie@example.com' },
5];
6
7const userList = users.map((user) => (
8 <li key={user.id}>
9 {user.name} - {user.email}
10 </li>
11));

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:

JAVASCRIPT
1// ❌ Bad practice: using index as key
2const userList = users.map((user, index) => (
3 <li key={index}>
4 {user.name} - {user.email}
5 </li>
6));
7
8// ✅ Good practice: using unique ID as key
9const userList = users.map((user) => (
10 <li key={user.id}>
11 {user.name} - {user.email}
12 </li>
13));

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

Continue with nearby questions from the same topic cluster.