A brief discussion on React Component life cycle functions

A brief discussion on React Component life cycle functions

What are the lifecycle functions of React components? Lifecycle functions only available to class components, including ES6 syntax classes and create-react-class modules:

It is divided into several stages: mounting, updating, uninstalling, and error handling ;

1. Mounting: constructor (commonly used), static getDerivedStateFromProps, render (commonly used), componentDidMount (commonly used)

The constructor is the constructor of the class component. You can initialize the state of the component or bind methods here, such as: constructor(props){ super(props);this.state={test: 'test'};this.someFn = this.someFn.bind(this);}, otherwise you don't need to explicitly implement the constructor method;

static getDerivedStateFromProps: Called before render, it can change the state by returning a value such as:

static getDerivedStateFromProps(nextProps, prevState){
 
    if(props.test !== state.test){
        return {state: props.state}; //The returned part is called partialState
//This will be part of the new state, nextState will be _assign({}, prevState, partialState);
    }
 
    return null; 
//If null or undefined is returned, nextState will be prevState, and the state of the component will not be changed;

Its only purpose is to let the component update state when props change, and the value of state depends on props; no matter for what reason, or if shouldComponentUpdate returns false in the component, it is executed before rendering;

The life cycle similar to static getDerivedStateFromProps is componentWillReceiveProps(nextProps), in which this.setState({...}); is called to change the state. Be cautious when using static getDerivedStateFromProps and componentWillReceiveProps, consider performance, and avoid bugs. If necessary, consider React.PureComponent or React.memo or fully controllable components or use key non-controllable components to replace the above getDerivedStateFromProps and componentWillReceiveProps.

There is also UNSAFE_componentWillReceiveProps which is triggered when the parent component is re-rendered;

Render is a rendering function that returns a React element. It is a method that class components must implement. It is a pure function that only returns a React element and does not interact directly with the interface. Interactions are generally placed in cycles such as ComponentDidMount or ComponentDidUpdate. The return value type of the render method can be:

//Can be a React element such as '<div/>' or '<MyComponent/>' 
//Or elements created with React.createElement(type, ?props, ?children),
//It can be an array (the array is similar to the form of this.props.children ['Test', ['nest test'], ...others])
//or Fragments,
//Can be a string or a numeric type (treated as a string),
//Can be Boolean type or null (when it is Boolean or null, nothing is rendered);
class Test extends React.Component {
    render(){
        //return 'Hello Test';
        //return true;
        //return ['Hello', ' Test'];
        //return <div>Test</div>
        //return <MyComponent>Test</MyComponent>
        return null;
    }
}

componentDidMount is called after the component is mounted to the React component tree; here you can get asynchronous data or rely on the initialization of DOM nodes, and it is also suitable to add subscriptions at this time (remember to unsubscribe when componentWillUnmount); calling setState here will trigger additional rendering, but it happens before the browser updates the screen, so even if render is called twice, the user cannot see the intermediate state;

2. Update: static getDerivedStateFromProps, shouldComponentUpdate, render (commonly used), getSnapshotBeforeUpdate, componentDidUpdate (commonly used)

shouldComponentUpdate: Available for components that inherit ReactComponent, but not for components that inherit React.PureComponent; Return true to update the component, otherwise, when shouldComponentUpdate returns false, the render method will not be called, and componentDidUpdate will not be called; shouldComponentUpdate(nextProps, nextState){} can manually compare this.props with nextProps, this.state with nextState; but if it returns false, it will not prevent the child component from re-rendering when the state is updated. Even if the child component is updated, it will not get the new props because the parent component has not been updated;

getSnapshotBeforeUpdate: called before the last rendering output (submitted to the DOM node), it can collect the current DOM information (such as the current DOM scroll position) before the element is submitted to the DOM, and then return to be passed to the componentDidUpdate cycle method (this method is called after the element is submitted to the DOM, so the DOM information obtained at this time is updated);

componentDidUpdate : componentDidUpdate(prevProps, prevState, snapshot){}; called after the component is updated, you can operate the DOM here, compare the props before and after, or request data asynchronously using state, etc.; the third parameter is the return value of the component's life cycle getSnapshotBeforeUpdate. If getSnapshotBeforeUpdate is not defined, the third parameter of componentDidUpdate is undefined;

3. Unmount: componentWillUnmount (commonly used)

componentWillUnmount: This cycle method is called before the component is uninstalled and destroyed; you can clear the timer, cancel the network request, cancel the subscription, etc. to release memory;

4, static getDerivedStateFromError, componentDidCatch;

static getDerivedStateFromError:

componentDidCatch:

Reference Documentation

React Component

This is the end of this article about the React Component lifecycle function. For more relevant React Component lifecycle content, please search for previous articles on 123WORDPRESS.COM or continue to browse the following related articles. I hope everyone will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • React new version life cycle hook function and usage detailed explanation
  • React State state and life cycle implementation method
  • React component life cycle example
  • React life cycle example analysis
  • React life cycle principle and usage notes
  • Comparison between Vue life cycle and react life cycle [recommended]
  • A brief discussion on the life cycle of components in React Native
  • React component life cycle detailed explanation
  • Commonplace js-react component life cycle
  • Interviewers often ask questions about React's life cycle

<<:  MySQL 8.0.15 installation tutorial for Windows 64-bit

>>:  Detailed explanation of the entry-level use of MySql stored procedure parameters

Recommend

Detailed explanation of scheduled tasks for ordinary users in Linux

Preface Ordinary users define crontab scheduled t...

How to use geoip to restrict regions in nginx

This blog is a work note environment: nginx versi...

Share some uncommon but useful JS techniques

Preface Programming languages ​​usually contain v...

VMware vSphere 6.7 (ESXI 6.7) graphic installation steps

Environment: VMware VCSA 6.7 (VMware-VCSA-all-6.7...

Detailed explanation of JS ES6 variable destructuring assignment

Table of contents 1. What is deconstruction? 2. A...

This article will show you how JavaScript garbage collection works

Table of contents 1. Overview 2. Memory Managemen...

SQL Aggregation, Grouping, and Sorting

Table of contents 1. Aggregate Query 1. COUNT fun...

List rendering instructions for efficient development of Vue front-end

v-for directive Speaking of lists, we have to men...

Summary of new usage examples of computed in Vue3

The use of computed in vue3. Since vue3 is compat...

JavaScript deshaking and throttling examples

Table of contents Stabilization Throttling: Anti-...

Detailed explanation of Angular component projection

Table of contents Overview 1. Simple Example 1. U...

Django+vue registration and login sample code

register The front-end uses axios in vue to pass ...

Research on the effect of page sidebar realized by JS

Table of contents Discover: Application of displa...