Lesson 25 of 60 – React Keys
42%

React Keys

Keys are special attributes used when rendering lists in React. A key helps React identify each item in a list so it can efficiently update the user interface when items are added, removed, or changed.

Note: A key should be unique among the items in the same list and should ideally be stable across renders.

1. What is a Key in React?

A key is a special React attribute that identifies an individual item when rendering a list.

const students = [
    { id: 1, name: "Rahul" },
    { id: 2, name: "Neha" }
];

function App() {

    return (
        <ul>

            {students.map(student => (
                <li key={student.id}>
                    {student.name}
                </li>
            ))}

        </ul>
    );

}

2. Why are Keys Needed?

React needs to identify individual list items when the list changes. Keys provide an identity for each item.

  • Identify list items.
  • Track changes between renders.
  • Identify added items.
  • Identify removed items.
  • Identify changed items.
  • Help React update the interface efficiently.

3. Basic Key Example

The key attribute is normally placed on the outermost element returned from the list operation.

{students.map(student => (
    <li key={student.id}>
        {student.name}
    </li>
))}

4. Keys Must Be Unique

Keys should be unique among the sibling elements in the same list.

Good:

{students.map(student => (
    <li key={student.id}>
        {student.name}
    </li>
))}

If every student has a different ID, each list item receives a different key.

5. Stable Keys

A good key should remain associated with the same item even when the list changes.

const students = [
    { id: 101, name: "Rahul" },
    { id: 102, name: "Neha" },
    { id: 103, name: "Amit" }
];

The student IDs provide stable identities for the list items.

6. Using an ID as a Key

A unique database or application ID is often a suitable key.

function StudentList({ students }) {

    return (
        <div>

            {students.map(student => (
                <div key={student.id}>

                    <h2>
                        {student.name}
                    </h2>

                </div>
            ))}

        </div>
    );

}

7. Keys and Strings

For a simple list containing unique strings, the string itself can sometimes be used as the key.

const courses = [
    "HTML",
    "CSS",
    "React"
];

{courses.map(course => (
    <li key={course}>
        {course}
    </li>
))}

This works when the values are unique within the list.

8. Keys and Numbers

Numbers can also be used as keys when they uniquely identify items.

const numbers = [10, 20, 30];

{numbers.map(number => (
    <li key={number}>
        {number}
    </li>
))}

9. Keys with Objects

When an array contains objects, a unique property such as id can be used as the key.

const products = [
    {
        id: 1,
        name: "Laptop"
    },
    {
        id: 2,
        name: "Keyboard"
    }
];

{products.map(product => (
    <p key={product.id}>
        {product.name}
    </p>
))}

10. Keys with Components

When rendering components from a list, the key should be placed on the component being returned.

function StudentCard({ name }) {

    return (
        <div>
            <h2>{name}</h2>
        </div>
    );

}

function App({ students }) {

    return (
        <div>

            {students.map(student => (
                <StudentCard
                    key={student.id}
                    name={student.name}
                />
            ))}

        </div>
    );

}

11. Key is Not a Normal Prop

The key attribute is used by React itself. It is not automatically available as a normal prop inside the child component.

function StudentCard(props) {

    console.log(props.key);

    return (
        <h2>
            {props.name}
        </h2>
    );

}

If the component needs the ID value, pass it separately as another prop.

<StudentCard
    key={student.id}
    id={student.id}
    name={student.name}
/>

12. Passing ID Separately

function StudentCard({ id, name }) {

    return (
        <div>

            <h2>
                {name}
            </h2>

            <p>
                Student ID: {id}
            </p>

        </div>
    );

}
<StudentCard
    key={student.id}
    id={student.id}
    name={student.name}
/>

13. What Happens Without a Key?

When rendering a list without keys, React can display a warning in development and loses the explicit identity information for those list items.

Example:

{students.map(student => (
    <li>
        {student.name}
    </li>
))}

A suitable key should be added to the list item.

14. Adding a Key

{students.map(student => (
    <li key={student.id}>
        {student.name}
    </li>
))}

Now React has a stable identifier for each student.

15. Keys and List Updates

Suppose a new student is added to a list. Keys help React determine which existing items remain the same and which item is new.

Before:

101 Rahul
102 Neha

After:

101 Rahul
102 Neha
103 Amit

The unique IDs allow React to identify the new item.

16. Keys and Removing Items

Keys also help React identify which item has been removed.

Before:

101 Rahul
102 Neha
103 Amit

After:

101 Rahul
103 Amit

React can identify that the item with key 102 is no longer present.

17. Keys and Reordering

Stable keys are especially useful when list items are reordered.

Before:

101 Rahul
102 Neha
103 Amit

After:

103 Amit
101 Rahul
102 Neha

The IDs continue to identify the same students even though their positions changed.

18. Array Index as Key

The array index can be used as a key in some simple cases.

{students.map((student, index) => (
    <li key={index}>
        {student}
    </li>
))}

However, this should be used carefully when list items can be reordered, inserted, or removed.

19. Why Index Keys Can Be Problematic

An index represents a position rather than the identity of an item. When the order of items changes, the same index may refer to a different item.

Before:

Index 0 → Rahul
Index 1 → Neha
Index 2 → Amit

After inserting a new item:

Index 0 → Priya
Index 1 → Rahul
Index 2 → Neha
Index 3 → Amit

The positions changed, even though the original students did not. Stable IDs can preserve item identity.

20. When Index Keys May Be Acceptable

Using an index as a key can be reasonable when the list is static and items are never reordered, inserted, or removed.

const months = [
    "January",
    "February",
    "March"
];

{months.map((month, index) => (
    <li key={index}>
        {month}
    </li>
))}

For dynamic lists, a stable unique ID is generally preferable.

21. Avoid Random Keys

Do not generate a new random key during every render.

For example, avoid:

{students.map(student => (
    <li key={Math.random()}>
        {student.name}
    </li>
))}

A changing random key prevents React from keeping a stable identity for the item.

22. Avoid Using Array Position for Dynamic Data

For dynamic data, using the item's unique identifier is generally better than its array position.

Prefer:

{students.map(student => (
    <StudentCard
        key={student.id}
        name={student.name}
    />
))}

This keeps the key connected to the student rather than the student's current position.

23. Keys with Filtered Lists

Keys should remain stable even when a list is filtered.

{students
    .filter(student => student.active)
    .map(student => (
        <li key={student.id}>
            {student.name}
        </li>
    ))
}

The student's ID remains the same even when other students are temporarily excluded.

24. Keys with Nested Lists

Each nested list should provide keys for its own list items.

const courses = [
    {
        id: 1,
        name: "React",
        topics: [
            "JSX",
            "Props",
            "State"
        ]
    }
];

{courses.map(course => (
    <div key={course.id}>

        <h2>
            {course.name}
        </h2>

        <ul>

            {course.topics.map(topic => (
                <li key={topic}>
                    {topic}
                </li>
            ))}

        </ul>

    </div>
))}

25. Keys with Fragments

When a list item needs to return multiple sibling elements, a keyed React Fragment can be used.

import { Fragment } from "react";

{students.map(student => (
    <Fragment key={student.id}>

        <h2>
            {student.name}
        </h2>

        <p>
            {student.course}
        </p>

    </Fragment>
))}

26. Key Warning

If React detects a list without suitable keys, development tools may show a warning such as a missing unique key warning.

The warning indicates that the rendered list should provide a suitable key for its items.

{students.map(student => (
    <li key={student.id}>
        {student.name}
    </li>
))}

27. Keys Should Come from Data

Whenever possible, use an identifier that already belongs to the data.

const students = [
    {
        id: "ST101",
        name: "Rahul"
    },
    {
        id: "ST102",
        name: "Neha"
    }
];

{students.map(student => (
    <StudentCard
        key={student.id}
        name={student.name}
    />
))}

28. Keys and Component State

Keys also affect how React associates component instances with list items. Stable keys help React keep the correct component identity when the list changes.

{students.map(student => (
    <StudentCard
        key={student.id}
        name={student.name}
    />
))}

For stateful list items, stable keys are particularly important when items can move or change.

29. Complete React Keys Example

function StudentCard({
    name,
    course
}) {

    return (
        <div className="card">

            <h2>
                {name}
            </h2>

            <p>
                Course: {course}
            </p>

        </div>
    );

}

function App() {

    const students = [
        {
            id: 101,
            name: "Rahul",
            course: "React"
        },
        {
            id: 102,
            name: "Neha",
            course: "JavaScript"
        },
        {
            id: 103,
            name: "Amit",
            course: "Python"
        }
    ];

    return (
        <div>

            <h1>
                Student List
            </h1>

            {students.map(student => (
                <StudentCard
                    key={student.id}
                    name={student.name}
                    course={student.course}
                />
            ))}

        </div>
    );

}

export default App;

Here, every student has a stable unique ID that is used as the key.

30. React Keys Best Practices

  • Always provide suitable keys when rendering lists.
  • Keys should be unique among sibling list items.
  • Prefer stable unique IDs from your data.
  • Avoid random values as keys.
  • Use array indexes carefully.
  • Index keys can be problematic for dynamic lists.
  • Remember that keys are used by React and are not automatically passed as props.
  • Pass the ID separately if the child component needs it.
  • Use keys when rendering reusable components from arrays.
  • Keep keys stable when list items are added, removed, or reordered.

📌 Key Points

  • Keys help React identify individual list items.
  • Keys should be unique among sibling elements.
  • Stable IDs are generally the preferred source for keys.
  • The key attribute is used internally by React.
  • The key is not automatically available through component props.
  • Pass an ID separately if the child component needs it.
  • Array indexes should be used carefully as keys.
  • Random values should not be used as keys.
  • Keys are especially important when lists change or are reordered.
  • Every rendered list item should have an appropriate key.

🧠 Quick Quiz

Question: What is the main purpose of the key attribute when rendering a list in React?