skip to Main Content

I’m a newbie to React and trying to understand key attribute of components.

According to the official documentation (emphasis mine),

You might be tempted to use an item’s index in the array as its key. In fact, that’s what React will use if you don’t specify a key at all. But the order in which you render items will change over time if an item is inserted, deleted, or if the array gets reordered. Index as a key often leads to subtle and confusing bugs.

but what kind of bugs can appear in addition to performance issue?

I’d like to see a concrete example code which is buggy due to the lack of key attribute, rather than an abstract textual explanation like "it would be buggy".

For example, the code below works as expected without the use of key (CodeSandbox):

import {useState} from "react";

export default function MyApp() {
    const [l, setL] = useState([
        {
            id: 0,
            name: "Apple",
        },
        {
            id: 1,
            name: "Orange",
        },
        {
            id: 2,
            name: "Grapes",
        },
    ]);

    return (
        <>
            <ul>
                {
                    l.map(e => {
                        return (
                            <div>
                                <li>{e.name}</li>
                                <button onClick={() => {
                                    const index = l.indexOf(e);
                                    let ll = [...l];
                                    ll.splice(index, 1);
                                    setL(ll);
                                }}>x</button>
                            </div>
                        );
                    })
                }
            </ul>
        </>
    );
}

2

Answers


  1. If you don’t specify any key React will specify ‘index’ as the key by default.
    Here is a code sandbox example where the code use ‘index’ as the key in the first table and ‘unique id’ as the key in the second table:

    Edit React withClickOutside (forked)

    You will notice that in the first table if you delete a row, it deletes it after 3 sec, but instead of removing ‘deleting..’ status from the row, it places it on the next row that now has the index of the previous row.

    As an index of the component can change in run time, we should avoid using the index to avoid this kind of error in run time. It also has many performance issues. I think you already found those from your research. All the best for your learning journey. I hope this answer was helpful.

    To learn more read this article: Reiterating why you should never use Array ‘index’ as ‘key’ in your React Applications

    Login or Signup to reply.
  2. Hope this article can help understand the role of key,Deep dive into React keys bugs

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search