The concept of Life Cycle is widely used, especially in many fields such as economy, environment, technology, society and so on. Its basic meaning can be colloquically understood as the whole process from Cradle to Grave

React component life cycle consists of creating, initializing data, compiling templates, mounting Dom, rendering, updating, rendering, and unmounting

The three stages

As you can see from the figure, the React component creation actually has multiple life cycles, which can be divided into three phases

Render phase

It is mainly used to calculate some current states

Features: pure and contains no side effects. React may be paused, suspended, or restarted.

The Pre – the commit phase

How about declaring commit? React actually updates the DOM node while mapping the current state to the DOM. There is no actual DOM update during the pre-commit phase

Features: DOM can be read

The Commit phase

React updates the state to the actual DOM nodes

Features: You can use DOM, run side effects, and schedule updates.

Three types of

When creating

When a component instance is created and inserted into the DOM, its lifecycle is invoked in the following order

  1. constructor(): a component constructor that is called before the component is updated to the interfaceconstructor
    1. Used to initialize internal state. Rarely used
    2. Only can be directly modifiedstateThe place where
  2. getDerivedStateFromProps(): Used to initialize some internal state from an external property
    1. whenstateNeed frompropsUsed during initialization
    2. Try not to use, maintainstate/propsState consistency adds complexity
    3. Every timerenderWill be called
    4. Typical scenario: Form controls get default values
  3. render(): a lifecycle method that the component must define to describeDOMstructure
  4. componentDidMount(): Used for data requests, defining some external resources and other side effects
    1. Called after UI rendering is complete
    2. Execute only once
    3. Typical scenario: Obtaining external resources

componentDidMount

If we place AJAX requests in other functions in the lifecycle, there is no guarantee that the request will require a response only after the component has been mounted.

If our data request completes before the component is mounted, and the setState function is called to add data to the component state, an error will be reported for the unmounted component.

Making an AJAX request in the componentDidMount function avoids this problem.

update

Updates are triggered when a component’s props or state changes. The lifecycle of component updates is called in the following order

  1. getDerivedStateFromProps(): Used to initialize some internal state from an external property
  2. shouldComponentUpdate(nextProps, nextState): Tells the component whether it needs to be rerendered for performance optimizations, such as determining the specificationpropsComponents are rerendered only when changes occur
    1. Determine the virtualDOMWhether you need to redraw
    2. In general, this can be done byPureComponentautomatically
    3. Typical scenario: Performance optimization
  3. render()
  4. getSnapshotBeforeUpdate(prevProps, prevState)
    1. Called before the last render output (submitted to the DOM node),stateHas been updated
    2. withcomponentDidUpdateCollocation is used
    3. Typical scenario: Capture the DOM state before render
  5. componentDidUpdate(prevProps, prevState)
    1. Called every time the UI is updated
    2. Typical scenario: The page needs to be based onpropsChange to retrieve data again

shouldComponentUpdate

ShouldComponentUpdate allows us to manually determine whether or not to update a component. Setting a reasonable return value for the component based on its application scenario helps us avoid unnecessary updates.

When unloading

When a component is removed from the DOM, when a component disappears from the page, it needs to be destroyed

The following methods are called:

  • componentWillUnmount(): Do something to free up resources and uninstall side effects

In this method necessary cleanup actions can be performed, such as clearing timer, canceling network request or clearing in

The lifecycle is required in error handling scenarios

The following methods are called when an error is thrown in the rendering process, lifecycle, or constructor of a child component

  • static getDerivedStateFromError()
  • componentDidCatch()

Common Usage Scenarios

  1. componentDidMount + componentWillUnmountImplement timers, such asDigital clock
class Clock extends React.Component {
  constructor(props) {
    super(props);
    this.state = { date: new Date() };
  }

  componentDidMount() {
    this.timerID = setInterval(() = > this.tick(), 1000);
  }

  componentWillUnmount() {
    clearInterval(this.timerID);
  }

  tick() {
    this.setState({
      date: new Date()}); }render() {
    return (
      <div>
        <h1>Hello, world!</h1>
        <h2>It is {this.state.date.toLocaleTimeString()}.</h2>
      </div>
    );
  }
}

ReactDOM.render(<Clock />.document.getElementById("root"));
Copy the code
  1. getSnapshotBeforeUpdate(prevProps, prevState) +componentDidUpdate()Capture scrollbar position

There’s a list of what’s going on in reality — list,

  1. It appears at the top of the list every time a new dynamic is created
  2. List supports scrolling so that users can view historical messages

If you don’t use getSnapshotBeforeUpdate, the scroll bar will scroll down every time a message comes in, so it won’t stay in place

Because each incoming message creates a new DOM node at the top,

To avoid this problem, we need to know

  1. Knowing the current height of the entire container before the page is updated,
  2. Know the new height of the container after the page is updated
  3. Compare the old height with the new height
  4. The height difference is added to the container after each page updatescrollTop

This ensures that the scrollbar stays in its current position even when new messages come in

// SnapshotSample.less
.snapshotSample {
  height: 100px;
  padding: 20px;
  overflow: auto;
  border: 1px solid #eee;
  widows: 300px;
}
Copy the code
import React, { PureComponent } from "react";

import styles from "./SnapshotSample.less";

export default class SnapshotSample extends PureComponent {
  constructor(props) {
    super(props);
    this.listRef = React.createRef();
    this.state = {
      list: [],}; }handleNewMessage() {
    this.setState((prev) = > ({
      list: [`msg ${prev.list.length}`. prev.list], })); }componentDidMount() {
    for (let i = 0; i < 20; i++) this.handleNewMessage();
    this.interval = setInterval(() = > {
      if (this.state.list.length > 200) {
        clearInterval(this.interval);
        return;
      }
      this.handleNewMessage();
    }, 1000);
  }
  componentWillUnmount() {
    clearInterval(this.interval);
  }

  getSnapshotBeforeUpdate(prevProps, prevState) {
    // Do we add new items to the list?
    // Capture the scroll position so we can adjust the scroll position later.
    if (prevState.list.length < this.state.list.length) {
      const list = this.listRef.current;
      return list.scrollHeight - list.scrollTop;
    }
    return null;
  }

  componentDidUpdate(prevProps, prevState, snapshot) {
    // If our snapshot has a value, we just added a new item,
    // Adjust the scroll position so that these new items do not push the old items out of the view.
    // (where snapshot is the return value of getSnapshotBeforeUpdate)
    if(snapshot ! = =null) {
      const list = this.listRef.current; list.scrollTop = list.scrollHeight - snapshot; }}render() {
    return (
      <div className={styles.snapshotSample} ref={this.listRef}>
        {this.state.list.map((msg) => (
          <div key={msg}>{msg}</div>
        ))}
      </div>); }}Copy the code

summary

  1. Understand the React component lifecycle approach
  2. Understand the usage scenarios for the lifecycle


The last

This article is shallow, you are welcome to see the officer comments left your opinion!

Feel the harvest of the students welcome to like, pay attention to a wave!

Past oliver

  • 15 front-end hd knowledge map, strongly recommended collection
  • What is the principle of qr code scanning login
  • Let me tell you about some awesome NPM packages
  • The most complete ECMAScript walkthrough
  • Front end developers should know Centos/Docker/Nginx/Node/Jenkins (🍡 long)