preface

The React lifecycle identifies the React component from birth (component creation) to death (component destruction). It provides specific function hooks (lifecycle functions) that allow developers to trigger custom actions at certain points (lifecycle nodes).

React Lifecycle Diagram (old version)

DOM life cycle

Before we look at the React lifecycle, let’s look at what the lifecycle of the native DOM looks like

let app = document.getElementById("app");

// create div
let div = document.createElement("div");

let state = 0;
div.innerHTML = `
  <p>${state}</p>
  <button>+</button>
  <button>die</button>
`;

// mount div
app.appendChild(div);

div.style.border = "1px solid red";

div.querySelector("button").onclick = function() {
  state += 1;
  // update div
  div.querySelector("p").innerText = state;
};

div.querySelectorAll("button") [1].onclick = function() {
  // Clear all references
  div.querySelector("button").onclick = null;
  div.querySelectorAll("button") [1].onclick = null;
  div.remove();
  div = null; 
  // destroy div
};
Copy the code

The above code describes the life cycle of a div, the creation and destruction process. If you understand this, the React life cycle is the same.

React life cycle diagram

Try writing the React lifecycle. Note that React has listed some lifecycle methods as unsafe since version 16.3. As to why these lifecycle methods are unsafe, React argues that these lifecycle methods are often misunderstood and subtly abused, and anticipates that this abuse could cause problems with asynchronous rendering. In version 17.0 will delete componentWillMount componentWillReceiveProps and componentWillUpdate. (Starting with this release, only the new “UNSAFE_” life cycle name is in effect.)

  • componentWillMount
  • componentWillReceiveProps
  • componentWillUpdate

React lifecycle

import React from "react";
import "./styles.css";

export default class App extends React.Component {
  constructor() {
    super(a);this.state = {
      count: 0
    };
    console.log("create");
  }
  onClick() {
    this.setState({
      count: this.state.count + 1
    });
  }
  UNSAFE_componentWillMount() {
    console.log("will mount");
  }
  componentDidMount() {
    console.log("did mount");
  }
  UNSAFE_componentWillUpdate() {
    console.log("will update");
  }
  componentDidUpdate() {
    console.log("did update");
  }
  render() {
    console.log("mount or update");
    return (
      <div className="App">
        {this.state.count}
        <button onClick={()= > this.onClick()}>+</button>
      </div>); }}/*console.log prints create will mount mount or update did mount will update mount or update did update */
Copy the code

UNSAFE_componentWillMount (); render (); componentDidMount (); When the rendered data is updated, the UNSAFE_componentWillUpdate hook is called before the update, the Render function is called again when the component is updated, and the componentDidUpdate hook is called after the update.