The React component lifecycle is divided into three parts

  • Mounting process (Mounting): The process of mounting the component into the DOM for the first time
  • Update process: The process when a component is re-rendered
  • Unmounting: The component is deleted from the DOM

Three different procedures. The React library calls component member functions in turn, called lifecycle functions. So to customize the React component, you essentially customize these lifecycle functions

1. Unsafe hook functions

Some of the older components have unsafe behavior. (Unsafe: not security, but code that uses these lifecyls may fail in future versions of React, especially with asynchronous rendering enabled.)

  • componentWillMount
  • componentWillReceiveProps
  • componentWillUpdate

In the past, the above three methods were often misinterpreted and abused, potentially causing more problems with asynchronous rendering, so V16.3 added the UNSAFE_ prefix to the front (old API use will be warned, V17.0 will remove the old API, enable the new API).

2. Mounting process

When a component is rendered for the first time, the following functions are called:

2.1 the constructor

The constructor is executed first, usually inside the constructor to initialize the state object or bind this to the custom method

2.2 getDerivedStateFromProps

GetDerivedStateFromProps V16.3 (new) : this name is a semantic, which means that access to start from the props, the actual function is to map the props to the state, getDerivedStateFromProps is a static function, This function cannot access the class property through this, and direct access to the property is not recommended. Instead, the nextProps and prevState parameters should be provided, and the new props should be mapped to state. If the props passed in does not need to affect your state, you need to return null, which is required

GetDerivedStateFromProps is called whenever the parent component raises the rendering process for the current component, giving us an opportunity to adjust the new props state based on the previous state

	static getDerivedStateFromProps (nextprops, prevState) {
		console.log('getDerivedStateFromProps' + nextprops.value)
		console.log('getDerivedStateFromProps start ' + prevState.count)
		return(nextprops.value ! == prevState.start) }Copy the code

2.3 render

React should not contain any other business logic. If there are components that are not part of the render interface, let the render function return null or false Ct, this component does not need to render any DOM elements this time

2.4 componentDidMount

ComponentDidMount: componentDidMount is called after the component is mounted. At this time, we can obtain the node on the DOM for operation, such as canvas, SVG operation, server request can be unloaded and can be inside

/ / the parent component
import React from 'react'
import AppCopy from './AppCopy.js'
class App extends React.Component {
	render () {
		return(
			<div>
				<AppCopy value=""/>
				<AppCopy value=""/>
			</div>
		)
	}
}
export default App
Copy the code
/ / child component
import React from 'react'

class AppCopy extends React.Component {
	constructor (props) {
		super(props)
		this.state = {
			count: props.value
		}
		console.log('1. Constructor run: constructor')
	}
	handle (e) {
		this.setState({count: e.target.value})
	}
	componentDidMount () {
		console.log('4. After mounting the DOM: componentDidMount')}static getDerivedStateFromProps (nextprops, prevState) {
		console.log('getDerivedStateFromProps' + nextprops.value)
		console.log('getDerivedStateFromProps start ' + prevState.start)
		return false
	}
	render () {
		console.log('3. Return JSX structure: render')
		return (
			<div>
				{this.state.count}
				<input type="text" value={this.state.count} onChange={ (e) = > {this.handle(e)}}></input>
			</div>)}}export default AppCopy
Copy the code

GetDerivedStateFromProps is render close to this, but componentDidMount is not render close, When the render function of both children of the parent component is called, the two components’ componentDidMount is called together

The render function itself does not render or load content into the DOM tree. It simply returns a JSX representation object. The React library then decides how to render based on the returned object. The React library must combine the results of all the components in order to know how to generate the corresponding DOM modification. Therefore, the React library only calls the Render function of the child components twice, and then calls the componentDidMount function of each component once End of loading process

3. Update process

When the component is loaded into the DOM tree, the user can see the first image of components on the web page, but to provide a better interaction experience, will make the component can be operated as the user to change the content of the show, when the props or state is modified, the result will be a component of the update process, function will call the following life cycle:

3.1 getDerivedStateFromProps(added in V16.3):

Also called in mount

3.2 shouldComponentUpdate:

ShouldComponentUpdate (nextProps,nextState) says render is important because the render function determines what to render, ShouldComponentUpdate is important because it determines when a component doesn’t need to render, and it returns a Boolean that tells the React library whether or not the component needs to continue during the update process. Call this function first during the update process, If this function returns true, the update continues downward, otherwise it stops and no subsequent rendering is triggered. Use this function properly and it will greatly improve the function of the React component. Although React rendering performance is already very good, no matter how fast the render is, if you find that there is no need to render for a long time, it will be faster

The render function is a pure function. The logical input of this pure function is props and start, so shouldComponentUpdate should be props and state. If you want to define shouldComponentUpdate, use these two parameters, plus this.props and this.state to determine whether to return true or false

If I add shouldComponmentUpdate to the component, Then continue to use the default implementation of all the components React parent React.Com ponent, the default implementation is simple returns true, also is the need to render each update process, it is the best solution, if the performance of the pursuit of perfection can’t satisfy the default implementation, it need to customize the function

This. SetState does not update the state value of the component immediately. This. State is still the value before this. So what we’re going to do is actually compare each other with nextProps, nextState, this.props, and this. state

3.3 render

The update phase also triggers this lifecycle

3.4 getSnapshotBeforeUpdate

GetSnapshotBeforeUpdate (prevProps,prevState), this method is called after Render and before componentDidUpdate with two parameters prevProps and prevState, Represents the previous property and the previous state, and this function returns a value, which is passed to componentDidUpdate as a third argument, and if you don’t want to return a value, you can return null, This life cycle must be used with componentDidUpdate (don’t use it, the official one is for Scroll, the rest is useless)

3.5 componentDidUpdate

ComponentDidUpdate (prevProps prevState, snapshot), the method after getSnapshotBeforeUpdate method is called, there are three parameters prevProps, prevState, snapshot, Represents previous props, previous state, and snapshot. The third argument is returned by getSnapshotBeforeUpdate, which migrates the comparison or calculation to getSnapshotBeforeUpdate if the DOM element state is needed to trigger some callback function. The callback or status update is then triggered uniformly in componentDidUpdate

When a server renders React, the Did function (componentDidUpdate) is not implemented only in the browser, and is executed regardless of whether the update occurs on the server or in the browser. You can also use componentDidUpdate to execute other JS libraries (such as Jquery). When React is updated, the original content is redrawn and Jquery code is called again at componentDidUpdate

React is a server rendering component that generates only the HTML string. A single loading process is enough to generate the HTML. So under normal circumstances, the server will not call componentDidUpdate function, if the call indicates that the program has an error, it needs to change

import React from 'react'

class AppCopy extends React.Component {
	constructor (props) {
		super(props)
		this.state = {
			count: props.value
		}
		console.log('1. Constructor run: constructor')
	}
	handle (e) {
		this.setState({count: e.target.value})
	}
	componentDidMount () {
		console.log('4. After mounting the DOM: componentDidMount')}static getDerivedStateFromProps (nextProps, prevState) {
		console.log('getDerivedStateFromProps' + nextProps.value)
		console.log('getDerivedStateFromProps start ' + prevState.count)
		return(nextProps.value ! == prevState.start) } getSnapshotBeforeUpdate(prevProps,prevState) {console.log('getSnapshotBeforeUpdate prevProps: ' + prevProps.value)
		console.log('getSnapshotBeforeUpdate prevState: ' + prevState.count)
		return null
	}
	componentDidUpdate (prevProps,prevState,snapshot) {
		console.log('componentDidUpdate prevProps: ' + prevProps.value)
		console.log('componentDidUpdate prevState: ' + prevState.count)
		console.log('componentDidUpdate snapshot: ' + snapshot)
	}
	shouldComponentUpdate (nextProps, nextState) {
		console.log('shouldComponentUpdate props' + nextProps.value)
		console.log('shouldComponentUpdate start ' + nextState.count)
		return true
	}
	render () {
		console.log('3. Return JSX structure: render')
		return (
			<div>
				{this.state.count}
				<input type="number" value={this.state.count} onChange={ (e) = > {this.handle(e)}}></input>
			</div>)}}export default AppCopy
Copy the code

4. Uninstall process

  • ComponentWillUnmount: Called directly before the component is unmounted and destroyed. This method performs necessary cleanup operations, such as cleaning timers, canceling network requests or cleaning subscriptions created in componentDidMount(), cleaning up invalid DOM elements, and so on.

The React component unmounts only one componentWillUnmount function, which is called back before the React component is removed from the DOM tree, so this function is good for some cleanup