Detailed description of the life cycle of React components

Detailed description of the life cycle of React components

1. What is the life cycle

The life cycle of a component is the working process of React, just like people are born, grow old, get sick and die, and there are changes in nature. Every component in a web page will be created, updated and deleted, just like a living organism.

The life cycle of a React component can be divided into three processes

  • Mounting process: It is the process of rendering the component in the DOM tree for the first time.
  • Update process: The process in which a component is re-rendered.
  • Unmounting process: The process of removing a component from the DOM.

2. Loading process

Call the following functions in sequence: constructor、getInitialState、getDefaultProps、componentWillMount、render、componentDidMount。

1.constructor

It is the constructor in ES6, which creates an instance of a component class. In this process, two steps are required: initializing the state and binding the this environment of the member function.

2. Render

Render is the most important function in React components. This is the only non-ignorable function in react. In the render function, there can only be one parent element. The render function is a pure function. It does not actually perform rendering actions. It is just a structure described by JSX. Ultimately, React will perform the rendering process. There should be no operations in the render function. The description of the page depends entirely on the return results of this.state and this.props. You cannot call this.setState in render.

  • There is a formula that summarizes it very vividly: UI=render(data)

3. componentWillMount and componentDidMount

These two functions are executed before and after render respectively. Since this process can usually only be called on the browser side, we get asynchronous data here, and when componentDidMount is called, the component has been loaded into the DOM tree.

3. Update process

Simply put, it is the process of modifying props and state, calling componentWillReceiveProps、shouldComponentUpdate、componentWillUpdate、render、componentDidUpdate。

1. componentWillReceiveProps(nextProps)

It is not called only when props change. In fact, as long as the render function of the parent component is called, the child component rendered in render will be updated. Regardless of whether the props passed from the parent component to the child component have changed, the componentWillReceiveProps process of the child component will be triggered. However, the triggering process of the this.setState method will not call this function, because this function is suitable for calculating whether to update the internal state based on the value of the new props.

2. shouldComponentUpdate(nextProps, nextState)

The importance of this function is second only to render. The render function determines what to render, while shouldComponentUpdate determines what does not need to be rendered. Both need to return functions. This process can improve performance and ignore unnecessary re-rendering processes.

3. componentWillUpdate and componentDidUpdate

Unlike the loading process, componentDidUpdate here can be executed on both the browser side and the server side.

4. Trigger render

In react, there are 4 paths that trigger render.

The following assumes that shouldComponentUpdate returns true by default:

(1) Initial Render

(2) Call this.setState (not every setState call will trigger a render. React may merge the operations and render them all at once).

(3) The parent component is updated (usually the props change, but even if the props do not change or there is no data exchange between the parent and child components, render will be triggered).

(4) Call this.forceUpdate.

insert image description here

Note: If you return false in shouldComponentUpdate, you can exit the update path early.

4. Uninstallation process

It is rarely used in practice. There is only one componentWillUnmount here. Generally, events registered in componentDidMount need to be deleted here.

5. Lifecycle Process

1. Initialize rendering and display for the first time: ReactDOM.render()

  • constructor(): Create an object and initialize state
  • componentWillMount() : callback to be inserted
  • render() : used to insert virtual DOM callback
  • componentDidMount() : callback has been inserted

2. Update state every time: this.setState()

  • componentWillUpdate() : callback to be updated
  • render() : update (re-render)
  • componentDidUpdate() : Updated callback

3. Remove components: ReactDOM.unmountComponentAtNode(containerDom)

  • componentWillUnmount(): The component will be removed.

6. Examples

 <div id='container'></div>
    <script type="text/babel">
        class LifeCycle extends React.Component {
            constructor(props) {
                super(props);
                alert("Initial render");
                alert("constructor");
                this.state = {str: "hello"};
            }
             componentWillMount() {
                alert("componentWillMount");
            }
            componentDidMount() {
                alert("componentDidMount");
            }
            componentWillReceiveProps(nextProps) {
                alert("componentWillReceiveProps");
            }
            shouldComponentUpdate() {
                alert("shouldComponentUpdate");
                return true; // Remember to return true
            }
             componentWillUpdate() {
                alert("componentWillUpdate");
            }
            componentDidUpdate() {
                alert("componentDidUpdate");
            }
            componentWillUnmount() {
                alert("componentWillUnmount");
            }
            setTheState() {
                let s = "hello";
                if (this.state.str === s) {
                    s = "HELLO";
                }
                this.setState({
                    str: s
                });
            }
            forceItUpdate() {
                this.forceUpdate();
            }
            render() {
                alert("render");
                return(
                    <div>
                        <span>{"Props:"}<h2>{parseInt(this.props.num)}</h2></span>
                        <br />
                        <span>{"State:"}<h2>{this.state.str}</h2></span>
                    </div>
                );
            }
        }
        class Container extends React.Component {
            constructor(props) {
                super(props);
                this.state = {
                    num: Math.random() * 100
                };
            }
            propsChange() {
                this.setState({
                    num: Math.random() * 100
                });
            }
            setLifeCycleState() {
                this.refs.rLifeCycle.setTheState();
            }
            forceLifeCycleUpdate() {
                this.refs.rLifeCycle.forceItUpdate();
            }
            unmountLifeCycle() {
                // Unmounting the parent component here will also cause the child component to be unmounted ReactDOM.unmountComponentAtNode(document.getElementById("container"));
            }
            parentForceUpdate() {
                this.forceUpdate();
            }
            render() {
                return (
                    <div>
                        <a href="javascript:;" onClick={this.propsChange.bind(this)}>propsChange</a>
                        &nbsp;&nbsp;&nbsp;
                        <a href="javascript:;" onClick={this.setLifeCycleState.bind(this)}>setState</a>
                        &nbsp;&nbsp;&nbsp;
                        <a href="javascript:;" onClick={this.forceLifeCycleUpdate.bind(this)}>forceUpdate</a>
                        &nbsp;&nbsp;&nbsp;
                        <a href="javascript:;" onClick={this.unmountLifeCycle.bind(this)}>unmount</a>
                        &nbsp;&nbsp;&nbsp;
                        <a href="javascript:;" onClick={this.parentForceUpdate.bind(this)}>parentForceUpdateWithoutChange</a>
                        <LifeCycle ref="rLifeCycle" num={this.state.num}></LifeCycle>
                    </div>
                );
            }
        }
        ReactDOM.render(
            <Container></Container>,
            document.getElementById('container')
        );
    </script>

Summarize

This article ends here. I hope it can be helpful to you. I also hope that you can pay more attention to more content on 123WORDPRESS.COM!

You may also be interested in:
  • React Class component life cycle and execution order
  • React component life cycle example
  • A brief discussion on the life cycle of components in React Native
  • React component life cycle detailed explanation
  • Commonplace js-react component life cycle

<<:  Solve the problem of Docker starting Elasticsearch7.x and reporting an error

>>:  Markodwn's detailed explanation of the idea of ​​synchronous scrolling with title alignment

Recommend

Vue Element-ui table realizes tree structure table

This article shares the specific code of Element-...

Code analysis of user variables in mysql query statements

In the previous article, we introduced the MySQL ...

XHTML Getting Started Tutorial: Using the Frame Tag

<br />The frame structure allows several web...

Realize three-level linkage of year, month and day based on JavaScript

This article shares the specific code for JavaScr...

How to use sed command to efficiently delete specific lines of a file

Preface Normally, if we want to delete certain li...

Implementation steps for installing Redis container in Docker

Table of contents Install Redis on Docker 1. Find...

In-depth analysis of MySQL indexes

Preface We know that index selection is the work ...

Review of the best web design works in 2012 [Part 1]

At the beginning of the new year, I would like to...

JavaScript data structure bidirectional linked list

A singly linked list can only be traversed from t...

Detailed explanation of basic syntax and data types of JavaScript

Table of contents Importing JavaScript 1. Interna...

Linux general java program startup script code example

Although the frequency of starting the shell is v...