Why is it not recommended to use index as key in react?

Why is it not recommended to use index as key in react?

1. Compare the old virtual DOM with the new virtual DOM, first check whether their keys are the same
2. Continue to compare their contents, and generate new real DOM for replacement.
3. If the content and key are the same, reuse the old real DOM without changing it

So what problems might arise if we use the index automatically generated during traversal as the key of each node? Here is a small case

First, we traverse persons at the beginning

He will be such a process, source data

persons:
{ id: 1, name: “张三”, age: 15 },
{ id: 2, name: “Li Si”, age: 16 },
],

Generated real DOM node

<ul>
      <li key="0">Zhang San--15</li>
      <li key="1">Li Si--16</li>
    </ul>

Then we insert a data of {id:3,name:'王五',age:14} in front of this list and it will become like this

<ul>
   <li key="0">Wang Wu--14</li>
      <li key="1">Zhang San--15</li>
      <li key="2">Li Si--16</li>
    </ul>

Through the above update, we can find that Wang Wu has occupied the previous key of Zhang San. That is to say, when I update this process, the new virtual dom

<li key="0">Wang Wu--14</li>

and the old virtual dom

<li key="0">Zhang San--15</li>

When comparing the new DOM, first compare the keys of the two to see if they are the same. When comparing the contents, one is Wang Wu-14 and the other is Zhang San 15. The content has changed. At this time, the new virtual DOM will be used to generate a new real DOM to re-render the page. Not only the previous Zhang San will be affected and need to be regenerated, but the subsequent Li Si will also be replaced by Zhang San to generate a new real DOM with the content of Zhang San. This will cause all DOMs to be regenerated and re-rendered, resulting in performance degradation.

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <script src="https://unpkg.com/react@16/umd/react.development.js"></script>
    <script src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
    <script src="https://unpkg.com/[email protected]/babel.js"></script>

    <div id="root"></div>
    <script type="text/babel">
      let root = document.getElementById("root");
      class App extends React.Component {
        constructor(props) {
          super(props);
        }
        state = {
          persons:
            { id: 1, name: "张三", age: 15 },
            { id: 2, name: "Li Si", age: 16 },
          ],
        };
        handle = () => {
          const { persons } = this.state;
          const p = {
            id: 0,
            name: "Wang Wu",
            age: 14,
          };
          this.setState({
            persons: [p, ...persons],
          });
        };
        render() {
          return (
            <div>
              <button onClick={this.handle}>Click to add</button>
              <ul>
                {this.state.persons.map((person, index) => (
                  <li key={index}>
                    {person.name}--{person.age}
                  </li>
                ))}
              </ul>
            </div>
          );
        }
      }
      ReactDOM.render(<App name="hell" />, root);
    </script>
  </body>
</html>

Imagine what would happen if we used id as the only key value after the above deduction.

Before update

<ul>
      <li key="1">Zhang San--15</li>
      <li key="2">Li Si--16</li>
    </ul>

After Update

<ul>
   <li key="0">Wang Wu--14</li>
      <li key="1">Zhang San--15</li>
      <li key="2">Li Si--16</li>
    </ul>

Although Wang Wu is inserted in front of Zhang San this time, he only compares Wang Wu and the node above to see if they have the same key=0 node. No new real DOM is generated for rendering. Zhang San is compared with the node above with key=1 and finds that there is a node with key=1. Then he compares their contents to see if they are the same. If they are the same, the old real DOM can be reused to save performance.

This is the end of this article about why it is not recommended to use index as key in react. For more relevant react index as key content, please search 123WORDPRESS.COM's previous articles or continue to browse the following related articles. I hope everyone will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • Why can't I use index as key when using v-for in Vue?
  • Detailed explanation of why index should not be used as key in Vue (diff algorithm)
  • Some things removed or changed in vue2.0 (removed index key)

<<:  Deleting files with spaces in Linux (not directories)

>>:  How to change the host name in Linux

Recommend

JavaScript jigsaw puzzle game

This article example shares the specific code of ...

HTML Editing Basics (A Must-Read for Newbies)

Open DREAMWEAVER and create a new HTML. . Propert...

Analyzing the MySql CURRENT_TIMESTAMP function by example

When creating a time field DEFAULT CURRENT_TIMEST...

Html+CSS drawing triangle icon

Let’s take a look at the renderings first: XML/HT...

Linux uses shell scripts to regularly delete historical log files

1. Tools directory file structure [root@www tools...

How to use CocosCreator for sound processing in game development

Table of contents 1. Basics of audio playback in ...

React Native startup process detailed analysis

Introduction: This article takes the sample proje...

How to check if a table exists in MySQL and then delete it in batches

1. I searched for a long time on the Internet but...

Native JS to achieve directory scrolling effects

Here is a text scrolling effect implemented with ...

Detailed explanation of Vue configuration request multiple server solutions

1. Solution 1.1 Describing the interface context-...

Summary of the differences between get and post requests in Vue

The operating environment of this tutorial: Windo...

Detailed tutorial for installing influxdb in docker (performance test)

1. Prerequisites 1. The project has been deployed...

Three methods of automatically completing commands in MySQL database

Note: The third method is only used in XSell and ...