-1

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>
        </>
    );
}
ynn
  • 3,386
  • 2
  • 19
  • 42
  • Does this answer your question? [Understanding unique keys for array children in React.js](https://stackoverflow.com/questions/28329382/understanding-unique-keys-for-array-children-in-react-js) – jsejcksn May 10 '23 at 06:22
  • @jsejcksn No. I've read it before posting this question. I think the link doesn't answer what I want to know: "in what concrete situations, what concrete kinds of bugs appear". – ynn May 10 '23 at 06:29
  • [^](https://stackoverflow.com/questions/76215376/minimal-example-react-code-which-is-buggy-due-to-the-lack-of-keys?noredirect=1#comment134404725_76215376) @ynn The answers at that question include exactly that information. – jsejcksn May 10 '23 at 07:18

2 Answers2

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

PH Saurav
  • 106
  • 6
  • Isn't the cause of the bug is directly manipulation DOM via `e.target.textContent = "Deleting...";` (i.e. mutating DOM without using state setter) rather than purely due to the lack of `key`s? It seemed, by creating a new state which holds the string `Delete`, index `key` version would work as well. – ynn May 10 '23 at 07:44
  • I just confirmed the last comment is correct. By removing the operation with a side effect (i.e. `e.target.textContent = "Deleting...";`) , index `key` version works: [CodeSandBox](https://codesandbox.io/embed/react-index-as-key-forked-fsb7fh?fontsize=14&hidenavigation=1&theme=dark). The only file changed is `ProductsWithIndexKey.js`: I introduced a new state `deletingStatus` of the type `Array`. – ynn May 10 '23 at 07:55
  • No, the cause of the bug isn't direct manipulation. If so it should also exist in the second scenario. The only difference between the two scenarios is index as key. Yes, to demonstrate potential complications, he used direct DOM manipulation, it's not recommended but this type of scenario isn't impossible. The main point is if some sort of manipulation happens in run time it may cause an unexpected error. This type of direct manipulation won't always be clear like this one. It may be subtle or done by a library you are using. So it's a good idea not to keep the potential for nasty errors. – PH Saurav May 10 '23 at 08:11
0

Hope this article can help understand the role of key,Deep dive into React keys bugs

Sky Clong
  • 141
  • 1
  • 8