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

Analysis of the problem of deploying vue project and configuring proxy in Nginx

1. Install and start nginx # Install nginx sudo a...

The visual design path of the website should conform to user habits

Cooper talked about the user's visual path, w...

Summary of Linux sftp command usage

sftp is the abbreviation of Secure File Transfer ...

How to use @media in mobile adaptive styles

General mobile phone style: @media all and (orien...

Tutorial on installing Ceph distributed storage with yum under Centos7

Table of contents Preface Configure yum source, e...

Detailed tutorial on installing Mysql5.7.19 on Centos7 under Linux

1. Download MySQL URL: https://dev.mysql.com/down...

Use pure CSS to disable the a tag in HTML without JavaScript

In fact, this problem has already popped up when I...

js implements the classic minesweeper game

This article example shares the specific code of ...

Summary of Docker common commands and tips

Installation Script Ubuntu / CentOS There seems t...

How to implement the builder pattern in Javascript

Overview The builder pattern is a relatively simp...

Summary of the understanding of virtual DOM in Vue

It is essentially a common js object used to desc...

About the pitfall record of Vue3 transition animation

Table of contents background Problem location Fur...

SQL IDENTITY_INSERT case study

Generally speaking, once a column in a data table...

An article teaches you to write clean JavaScript code

Table of contents 1. Variables Use meaningful nam...