What’s the function of the key in the React list component? The following shows the functions of keys in list components by analyzing two demos with and without keys in list components.

1. There is no key in the list component

Directly on the code:

import React, { Component, Fragment } from 'react';
import ReactDOM from 'react-dom';

class App extends Component {
    constructor(props) {
        super(props);
        this.state = {
            list: ['a', 'b', 'c'],
        };
        this.handleClick = this.handleClick.bind(this);
    }

    handleClick() {
        const list = [...this.state.list];
        list.splice(1, 1);
        this.setState({list});
    }

    render() {
        const { list } = this.state;
        return (
            <Fragment>
                <ul>
                    {
                        list.map((item, index) => {
                            return (<li key={ index }>{ item }</li>);
                        })
                    }
                </ul>
                <button onClick={ this.handleClick }>Click</button>
            </Fragment>
        );
    }
}


ReactDOM.render(<App />, document.getElementById('root'));
Copy the code

The idea is simple: when I click the button, I remove a list item. Because there is no explicit key, React uses index index as the key for list items by default, so using index index as the key is the same as if there were no keys in component lists. Here’s what React does when the React button is clicked:

  1. When the button is clicked, the setState method is executed and state.list becomes [‘a’, ‘c’];
  2. Execute render method to generate a new virtual DOM tree, the old and new virtual DOM tree as shown below;
  3. The React list entries find the corresponding old and new virtual DOM objects with the same key, so the old virtual DOM ‘a’ object will be compared to the new virtual DOM ‘a’ object with the same result. The real DOM nodes corresponding to the old virtual DOM ‘A’ object in the real DOM tree remain unchanged, and the new virtual DOM ‘C’ object is compared with the old virtual DOM ‘b’ object. The result is different. The real DOM nodes corresponding to the real DOM tree and the old virtual DOM ‘b’ object are removed. A real DOM node corresponding to the new virtual DOM ‘c’ object is created in the real DOM tree. The ‘C’ object in the old virtual DOM tree has no comparable object in the new virtual DOM tree. The real DOM tree removes the real DOM node corresponding to the old virtual DOM ‘C’ object. To sum up, two DOM node removals and one DOM node addition are performed in the real DOM tree.
  4. Render the page according to the actual DOM manipulation.

2. The list component contains a key

Directly on the code:

import React, { Component, Fragment } from 'react';
import ReactDOM from 'react-dom';

class App extends Component {
    constructor(props) {
        super(props);
        this.state = {
            list: ['a', 'b', 'c'],
        };
        this.handleClick = this.handleClick.bind(this);
    }

    handleClick() {
        const list = [...this.state.list];
        list.splice(1, 1);
        this.setState({list});
    }

    render() {
        const { list } = this.state;
        return (
            <Fragment>
                <ul>
                    {
                        list.map((item) => {
                            return (<li key={ item }>{ item }</li>);
                        })
                    }
                </ul>
                <button onClick={ this.handleClick }>Click</button>
            </Fragment>
        );
    }
}


ReactDOM.render(<App />, document.getElementById('root'));
Copy the code

The only difference between this demo and the previous one is that it uses the table item as the key. Here’s what happens when the React button is clicked:

  1. When the button is clicked, the setState method is executed and state.list becomes [‘a’, ‘c’];
  2. Execute render method to generate a new virtual DOM tree, the old and new virtual DOM tree as shown below;
  3. The new virtual DOM object is compared with the old virtual DOM object. The old virtual DOM ‘a’ object is compared with the new virtual DOM ‘a’ object, and the result is the same. The real DOM node corresponding to the old virtual DOM ‘A’ object in the real DOM tree remains unchanged. The new virtual DOM ‘c’ object is compared with the old virtual DOM ‘C’ object, and the result is the same. The real DOM node corresponding to the old virtual DOM ‘C’ object in the real DOM tree remains unchanged. The ‘B’ object in the old virtual DOM tree has no comparable object in the new virtual DOM tree. Real DOM tree removes real DOM nodes corresponding to the old virtual DOM ‘b’. To sum up, remove the DOM node once in the real DOM tree.
  4. Render the page according to the actual DOM manipulation.

conclusion

Comparing the above two analysis processes, it can be concluded that there is a key in the list component, and the key value is not an index, which will reduce redundant DOM operations and improve web page performance. DOM manipulation is a performance-intensive affair, so when writing list components, it is best to use unique identifiers as key values for list items.