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

How to ensure the overall user experience

Related Articles: Website Design for User Experien...

Go to another file after submitting the form

<br />Question: How to write in HTML to jump...

MySQL performance optimization: how to use indexes efficiently and correctly

Practice is the only way to test the truth. This ...

Zabbix configuration DingTalk alarm function implementation code

need Configuring DingTalk alarms in Zabbix is ​​s...

MySQL data duplicate checking and deduplication implementation statements

There is a table user, and the fields are id, nic...

How to quickly install Nginx in Linux

Table of contents What is nginx 1. Download the r...

Detailed analysis of binlog_format mode and configuration in MySQL

There are three main ways of MySQL replication: S...

Automatic backup of MySQL database using shell script

Automatic backup of MySQL database using shell sc...

How to use Vue's idea to encapsulate a Storage

Table of contents background Function Purpose Ide...

How to build mysql master-slave server on centos7 (graphic tutorial)

This article mainly introduces how to build a MyS...

js implements the classic minesweeper game

This article example shares the specific code of ...

A brief discussion on value transfer between Vue components (including Vuex)

Table of contents From father to son: Son to Fath...