Don’t you know about the new life cycle after React16.3?

  Front end, javascript, Programmer, react.js

React16.3.0 started with some changes in the life cycle. This article mainly introduces the life cycle after React16.3.0.

Life cycle before React16.3.0:

I believe everyone is already familiar with the life cycle of react components before version 16. Version 16 react has made some modifications to the life cycle function of the component, which will be described in detail below.

Life cycle before React16.3.0

Creation period:

  1. constructor(props, context)
  2. componentWillMount()
  3. render()
  4. componentDidMount()

At runtime:

When props changes

  1. componentWillReceiveProps(nextProps, nextContext)
  2. shouldComponentUpdate(nextProps, nextState, nextContext)
  3. componentWillUpdate(nextProps, nextState, nextContext)
  4. render
  5. componentDidUpdate(prevProps, prevState, snapshot)

When the state changes

  1. shouldComponentUpdate(nextProps, nextState, nextContext)
  2. componentWillUpdate(nextProps, nextState, nextContext)
  3. render
  4. componentDidUpdate(prevProps, prevState, snapshot)

When unloading

componentWillUnmount()

Life cycle after React16.3.0

Creation period:

  1. constructor(props, context)
  2. static getDerivedStateFromProps(props, status)
  3. render()
  4. componentDidMount()

Or the following life cycle:

  1. constructor(props, context)
  2. componentWillMount() / UNSAFE_componentWillMount()
  3. render()
  4. componentDidMount()

Note: If GetDerivedStateFromPlops/GetSnapshotForUpdate and ComponentwillMount/ComponentwillReceiveProps/ComponentwillUpdate exist at the same time, React will give a warning message in the console. And only GetDerivedStateFromOps/GetSnapshotForUpdate [REACT @ 16.7.0] is executed

At runtime:

When props changes

  1. static getDerivedStateFromProps(props, status)
  2. shouldComponentUpdate(nextProps, nextState, nextContext)
  3. render
  4. getSnapshotBeforeUpdate(prevProps, prevState)
  5. componentDidUpdate(prevProps, prevState, snapshot)

Or the following life cycle:

  1. componentWillReceiveProps(nextProps, nextContext)/UNSAFE_componentWillReceiveProps
  2. shouldComponentUpdate(nextProps, nextState, nextContext)
  3. componentWillUpdate(nextProps, nextState, nextContext)
  4. render
  5. componentDidUpdate(prevProps, prevState, snapshot)

When the state changes

  1. static getDerivedStateFromProps(props, status)
  2. shouldComponentUpdate(nextProps, nextState, nextContext)
  3. render
  4. getSnapshotBeforeUpdate(prevProps, prevState)
  5. componentDidUpdate(prevProps, prevState, snapshot)

Or the following life cycle:

  1. shouldComponentUpdate(nextProps, nextState, nextContext)
  2. componentWillUpdate(nextProps, nextState, nextContext)/UNSAFE_componentWillUpdate
  3. render
  4. componentDidUpdate(prevProps, prevState, snapshot)

At the time of destruction

componentWillUnmount()

New Lifecycle Diagram:

clipboard.png

Detailed explanation of life cycle

1.constructor(props, context)

The constructor life cycle, if not required, is the default. State and bound event handlers are usually initialized in the constructor method.
However, if the constructor is written, super(props) must be called in it; Otherwise, errors may be reported.

For example:

class Base extends Component {
    constructor(props) {
        super();  //应该为 super(props);
    }
    state = {
        name: this.props.name
    }
    //....code
}

Exception thrown: uncaught typeerror: cannotreadproperty ‘name’ of undefined.

Similarly, if a context is defined, this.context needs to be used in the state to get the content on the context, then super(props, context) is required;

However, if you default to constructor, you can safely use this.props or this.context in the state without causing errors.

class Base extends Component {
    state = {
        name: this.props.name,
        color: this.context.color
    }
    //....code
}

The initialized state can also be defined in the constructor. If you need to bind this to a method, then unification is done in the constructor.

2.static getDerivedStateFromProps(props, state)

This method can be called when the state of a component needs to be changed according to props. This method is executed before rendering (). This method is triggered each time before rendering is triggered.

The method has two parameters props and state; The return value is a state object. You do not need to return the whole state, but return the state that needs to be changed. If not, null can be returned.

class Base extends Component {
    state = {
        age: 20
    }
    static getDerivedStateFromProps(props, state) {
        return {
            age: 50
        }
    }
    render() {
        // 50
        return (
            <div>{this.state.age}</div>
        )
    }
}

This method allows a component to update its internal state based on changes in props. The component state obtained in this way is called a derived state. Derivative states should be used cautiously, which may lead to potential errors.

3.render

The methods that must be provided in React components. When any data of state or props is updated, it will be executed.

Render () is a pure function, therefore, do not perform setState and other operations in it. Render must have a return value, which can have the following data types:

  • null、String、Number、Array、Boolean。
  • React elements
  • Fragment
  • Portal

Be careful not to call setState in render

4.componentDidMount

The componentDidMount () method is executed immediately after the component is loaded, that is, when the dom node associated with the component is inserted into the dom tree. This method is executed only once in the life of the component.
In general, we will setState () here, or make interface requests, set subscriptions, etc.

class Base extends Component {
    state = {
        age: 20
    }
    componentDidMount() {
        this.fetchDate();
    }
    render() {
        return (
            <div>{this.state.age}</div>
        )
    }
    //other code
}

5.shouldComponentUpdate(nextProps, nextState, nextContext)

Before rendering the new props or state, shouldComponentUpdate is called and returns true by default. This method is not called when forceUpdate ().

If shouldcomponentDidUpdate () returns false, getSnapshotBeforeUpdate,render, and ComponentUpdate will not be called.

This lifecycle is primarily used to optimize performance.

6.getSnapshotBeforeUpdate(prevProps, prevState)

Called before the output of render () is rendered to DOM. Enables components to capture current values (such as scroll positions) before they are changed. Any value returned by this life cycle will be passed as the third parameter to componentDidUpdate ().

7.componentDidUpdate(prevProps, prevState, snapshot)

Call componentDidUpdate () after the update occurs. When the component is updated, use this as an opportunity to manipulate the DOM. If the current props is compared with the previous props (for example, if the props has not changed, a network request may not be required.

If the component uses getSnapshotBeforeUpdate (), the value it returns will be passed to componentDidUpdate () as the third “snapshot” parameter. Otherwise, this parameter is undefined.

8.componentWillUnmount()

Called immediately before the component is unloaded and destroyed. Perform any necessary cleanup in this method, such as invalidating the timer, canceling the network request, or cleaning up any snoops created in componentDidMount ().

Finally, make one point:

The three life cycles of ComponentwillUpdate, ComponentwillReceiveProps, ComponentwillUpdate will be abandoned in the future version of React.

However, the future versions of Unsafe _ ComponentwillUpdate, Unsafe _ ComponentwillReceiveProps, Unsafe _ ComponentwillUpdate can still be used.

Initialization phase (parent and child components):

clipboard.png

Runtime: Parent Component props/state Update

If the shouldComponentUpdate of the child component returns false, the subsequent life cycle of the child component is not in progress, but the life cycle of the parent component continues to execute.

clipboard.png

Uninstall Phase: Uninstall Parent Component

clipboard.png

If this blog post gives you some inspiration or help, please give my github a Star:https://github.com/YvetteLau/ …

Reference:

  1. https://segmentfault.com/a/11 …
  2. https://www.jianshu.com/p/514 …
  3. https://blog.csdn.net/qq_2931 …