React Series 6: life cycle


Come and join us!

“Rookies of Xiaohe mountain”, provide technology related information and a series of basic articles for front-end developers. For a better user experience, please move to our official website Xiaoheshan rookies( )Study and get the latest articles in time.

“Code tailor”, if you are interested in our article or want to make some suggestions, please pay attention to wechat“Rookies of Xiaohe mountain”Official account, and contact with us, you can also read our articles on WeChat. Every suggestion or approval is a great encouragement to us!


In this section, we will introduceReactThe life cycle of components in, and the declaration cycle functions associated with the life cycle.

be careful:The life cycle introduced in this article is react 17.0.1, which may be changed in the reader’s period. Please focus on the official website for the final life cycle and other methods and processes

This article will introduce you to the following:

  • Understanding life cycle
  • Life cycle analysis
  • Common life cycle functions
  • Infrequently used life cycle

Understanding life cycle

Many things have the whole process from creation to destruction, which is calledlife cycle

ReactComponents also have their own life cycle. Understanding the life cycle of components can enable us to complete the functions we want in the most appropriate place;

After different life cycles of components, different life cycle functions will be triggered. Let’s write logic in the most appropriate place.

For example:

If a component needs to call the network to request data during generation, it shouldcomponentDidMount()Method to request the network.

be careful:Let’s talkReactIn life cycle, we mainly talk about the life cycle of classes, because functional components have no life cycle function;

Life cycle analysis

Each class component contains “life cycle methods”. You can rewrite these methods to facilitate the execution of these methods at a specific stage in the running process. Let’s learn about these life cycle functions. The following is the official life cycle map:

React Series 6: life cycle

When mounting:

  • When we mount a component, we execute it firstconstructorConstruct methods to create components;
  • Then it callsgetDerivedStateFromProps, it should return an object to updatestate, if returnednullThen nothing is updated.
  • Next callrenderFunction to get the to renderDOMStructure(jsx), and start renderingDOM
  • When the component is mounted successfully(DOMWhen rendering is complete, thecomponentDidMountLife cycle function;

When updating:

  • When we pass the modificationprops, or callsetStateModify the internal state or call directlyforceUpdateWill be called again whenrenderFunction to update;
  • When componentpropsorstateUpdates are triggered when changes occur. ThegetDerivedStateFromProps, it should return an object to updatestate, if returnednullThen nothing is updated.
  • Then it callsshouldComponentUpdateAnd judge whether the output of the react component is affected by the current state or props change according to the return value of this function.
  • Then it will callrenderFunction, which is calledgetSnapshotBeforeUpdate, perform the update operation
  • When the update is complete, a callback occurscomponentDidUpdateLife cycle function;

When uninstalling:

  • When our components are no longer used, they will be removed fromDOMRemove (unload) in the middle;
  • This time will call backcomponentWillUnmountLife cycle function;

Common life cycle functions



render()The method isclassThe only method in the component that must be implemented.

WhenrenderWhen called, it checksthis.propsandthis.stateAnd returns one of the following types:

  • React element。 Usually throughJSXestablish.
  • Arrays or fragments。 bringrenderMethod can return multiple elements.
  • Portals。 You can render child nodes to different nodesDOMIn the subtree.
  • String or numeric type。 They areDOMIs rendered as a text node
  • Boolean type ornull。 Nothing.

render()The function should be a pure function, which means that the component is not modifiedstateIn this case, each call returns the same result, and it does not interact directly with the browser.

To interact with your browser, clickcomponentDidMount()Or other lifecycle methods. keeprender()For pure functions, you can make components easier to think about.

be careful:IfshouldComponentUpdate()returnfalse, is not calledrender()



If not initializedstateOr no method binding is requiredReactComponent implementation constructor.

constructorThere are usually only two things to do in a job:

  • By givingthis.stateAssign an object to initialize the internalstate
  • Binding instances for events(this);
constructor(props) {
  //Do not call this. Setstate() here
  this.state = { counter: 0 };
  this.handleClick = this.handleClick.bind(this);

Can only be directly in the constructorthis.stateAssignment. To assign values in other methods, you should usethis.setState()replace.

be careful:Avoid willpropsValue assigned tostate! This is a common mistake



componentDidMount()Called immediately after the component is mounted (inserted into the DOM tree).

componentDidMountWhat are the usual operations in?

  • Depend onDOMThe operation of can be carried out here;
  • Sending network requests here is the best place( (official recommendation)
  • You can add some subscriptions here (see below)componentWillUnmountUnsubscribe);


componentDidUpdate(prevProps, prevState, snapshot)

componentDidUpdate()Will be called immediately after the update, and this method will not be executed for the first rendering.

  • After the component is updated, you can update it hereDOMOperation;
  • If you are interested in before and after the updatepropsAfter comparison, you can also choose to make a network request here( For example, whenpropsWhen there is no change, the network request is not executed).
componentDidUpdate(prevProps) {
  //Typical usage (don't forget to compare props):
  if (this.props.userID !== prevProps.userID) {

You can alsocomponentDidUpdate()inDirect callsetState(), but please noteIt must be wrapped in a conditional statement, as in the above example, otherwise it will lead to an endless loop.

be careful:IfshouldComponentUpdate()The return value isfalse, is not calledcomponentDidUpdate()



componentWillUnmount()It will be called directly before the component is unloaded and destroyed.

  • In this method, perform the necessary cleanup operations, such as cleanuptimerCancel network request or clear atcomponentDidMount()Subscriptions created in;
  • componentWillUnmount()inShould not callsetState()Because the component will never be re rendered. After the component instance is uninstalled, it will never be mounted again.

The code validates the above commonly used life cycle functions:

import React, { Component } from 'react'

class HYTestCpn extends Component {
  render() {
    return <h2>HYTestCpn</h2>

  componentWillUnmount() {
    console.log('HYTestCpn componentWillUnmount')

export default class App extends Component {
  constructor(props) {

    this.state = {
      counter: 0,

    Console.log ('call constructor method ')

  render() {
    Console.log ('call render method ')
    return (
        <h2>Current count: {this. State. Counter}</h2>
        {this.state.counter <= 5 && <HYTestCpn />}
        <button onClick={(e) => this.increment()}>+1</button>

  increment() {
      counter: this.state.counter + 1,

  componentDidMount() {
    Console.log ('call componentdidmount method ')

  componentDidUpdate() {
    Console.log ('call componentdidupdate method ')

  componentWillUnmount() {
    Console.log ('call componentwillunmount method ')

Infrequently used life cycle

In addition to the common life cycle functions described above, there are also some uncommon life cycle functions:


shouldComponentUpdate(nextProps, nextState)

WhenpropsorstateWhen changes occur,shouldComponentUpdate()Is called before rendering is executed. The default return value istrue。 First render or useforceUpdate()This method is not called when.

  • according toshouldComponentUpdate()Return value of, judgmentReactWhether the output of the component is affected by the currentstateorpropsImpact of changes.
  • The default behavior isstateThe component re renders each time it changes. In most cases, you should follow the default behavior.
  • This method is only used asWays to optimize performanceAnd exist. Do not attempt to rely on this method to “block” rendering, as this may producebug

We should first consider using built-inPureComponentassemblyInstead of writing it manually,PureComponentYespropsandstateShallow comparisons are made and the possibility of skipping necessary updates is reduced.

If you need to write it manually, you canthis.propsAndnextPropsas well asthis.stateAndnextStateCompare and returnfalseTo informReactUpdates can be skipped.Note that returnfalseIt does not prevent subcomponents from re rendering when the state changes.


static getDerivedStateFromProps(props, state)

getDerivedStateFromPropsWill be calledrenderThe method is called before and is invoked at the initial mount and subsequent updates.

  • It should return an object to updatestate, if returnednullThen nothing is updated.
  • getDerivedStateFromPropsThere is only one purpose: to make componentsProps changeUpdate whenstate, i.estateThe value of depends at all times onprops
  • This method does not have permission to access the component instance.

be careful:Whatever the reason, this method is triggered before each rendering.


getSnapshotBeforeUpdate(prevProps, prevState)

stayReactto updateDOMA function called back before can getDOMSome information before update (such as scroll position);

  • Any return value for this lifecycle is passed as a parameter tocomponentDidUpdate()
  • This usage is not common, but it may appear inUIProcessing, such as chat threads that need to process the scroll position in a special way.
  • Should returnsnapshotValue of (ornull)。

In addition,ReactSome out of date lifecycle functions are also provided in, which are no longer recommended.

For more details about the life cycle, please refer to react’s official website