Component life cycle

React strictly defines the component lifecycle, which may go through the following three processes:

  • The Mount process, which renders the component in the DOM tree for the first time;
  • Update, the process by which components are re-rendered;
  • Unmount, the process by which components are removed from the DOM.

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

The loading process

Let’s start with the loading process. When the component is first rendered, the following functions are called in sequence:

  • constructor
  • getInitialState
  • getDefaultProps
  • componentWillMount
  • render
  • componentDidMount
  1. constructor

We’ll start with constructor, the constructor for each class in ES6. To create an instance of a component class, the corresponding constructor will of course be called.

Note that not every component needs to define its own constructor. As we’ll see in later sections, stateless React components do not need to define constructors. A React component needs constructors for the following purposes:

  • Initialize state, because any function in the lifecycle of the component may need to access state, so the first constructor called in the lifecycle is naturally the best place to initialize state;
  • Bind the this environment of member functions

Under ES6 syntax, the this of each member function of a class is not automatically bound to the class instance when executed. In the constructor, this is the current component instance, so it is common to bind the instance’s specific function to this as the current instance in the constructor for convenience of future calls.

	this.onClick = this.onClick.bind(this);
Copy the code

When the onClick function in the current instance is called through bind, this always refers to the current component instance.

Pay attention to

In some tutorials, you’ll see another way to use bind, like this:

	this.onClick = ::this.onClick;
Copy the code

The double-colon: : operator used here is called bind, and although Babel supports it, bind may not be part of the ES standard syntax, so we don’t usually use it, even though it looks neat.

  1. GetInitialState and getDefaultProps

The return value of getInitialState will be used to initialize the component’s this.state. However, this method only works with component classes created using the react. createClass method.

The return value of the getDefaultProps function can be used as the initial value of the props. Like getInitialState, this function is only used in component classes created by the React. CreateClass method. In general, the getInitialState and getDefaultProps methods are not actually used in the React component of ES6’s method definition.

If we define a component Sample with the React. CreateClass method and set the initial value of the internal state foo to the string bar and the initial value of a prop called sampleProp to the numeric value 0, the code looks like this:

const Sample = React.createClass({
      getInitialState: function() {
        return { foo: 'bar' }
      },
      getDefaultProps: function() {
      	return { sampleProp: 0 }
      }
 })
Copy the code

In ES6, we initialize the state by assigning this. State to the constructor, and by assigning the props initial value to the class attribute defaultProps, we get exactly the same effect:

class Sample extends React.Component {
  constructor(props) {
    super(props);
    this.state = { foo: 'bar' };
  }
}
Sample.defaultProps = {
  return { sampleProp: 0 }
}
Copy the code

React.createClass has been officially deprecated by Facebook, but there are plenty of books on how to use react. createClass that can be found on the Internet. It is highly recommended that you stop using react. createClass, but if you do use it, It is important to note that getInitialState occurs only during the load process, meaning that the function is called only once during the lifetime of a component. Do not put code in it that is expected to be executed multiple times.

  1. render

The Render function is arguably the most important function in the React component. A React component can ignore all other functions, but it must implement the render function because the React.componentclass of all React components has a default implementation for life cycle functions other than render.

Usually for a component to function, it always renders something, the Render function doesn’t do the actual render action, it just returns a structure described by JSX, and React handles the render process.

The render function returns null or false, which tells React that the component doesn’t need to render any DOM elements this time.

Note that the render function should be a pure function, depending entirely on this.state and this.props, without any side effects. Calling this.setState in the render function is definitely wrong, because a pure function should not cause state changes.

  1. ComponentWillMount and componentDidMount

During loading, componentWillMount is called before the render function is called, and component-didmount is called after the render function is called. These two functions are like the front and back of the render function, one in front of the other, clamping the render function. Just do the necessary work before and after render respectively.

As the name implies, componentWillMount occurs when “about to be loaded”. There is no render result at this point, and even calling this.setState to change the state does not cause a redraw. It’s too late. In other words, everything that can be done in component-willmount can be done before constructor, and the main purpose of this function is to be symmetric with componentDidMount.

And componentWillMount’s sibling componentDidMount is very useful. Note that componentDidMount is not called immediately after the Render function is called. When componentDidMount is called, the render function returns something that has already been rendered, and the component has already been “loaded” into the DOM tree.

ComponentWillMount () componentDidMount (); componentWillMount (); componentDidMount (); ComponentDidMount is only called on the browser side, not on the server side when React is used.

The update process

After the component is loaded into the DOM tree, the user can see the first impression of the component on the web page, but to provide a better interactive experience, the component should be able to change the presentation as the user operates. When the props or state is changed, the component update process is triggered.

  • componentWillReceiveProps
  • shouldComponentUpdate
  • componentWillUpdate
  • render
  • componentDidUpdate
  1. componentWillReceiveProps(nextProps)

About the componentWillReceiveProps exist some misunderstandings. Some textbooks on the Internet claim that this function is called only when the props of the component are changed, which is not true. In fact, whenever the render function of the parent component is called, the child component is updated, triggering the componentWill-receiveprops function of the child component regardless of whether the props of the parent component to the child component are changed.

Note that the update triggered by the this.setState method does not call this function, because this function is suitable for calculating whether to update the internal state based on the new props value (the parameter nextProps). Update the status of the components is enclosing setState, if this calls setState cause componentWillReceiveProps is called again, it’s an infinite loop.

  1. shouldComponentUpdate(nextProps, nextState)

Aside from the Render function, shouldComponentUpdate is probably the most important function in the React component lifecycle. The render function is important because it determines what to render, and the shouldComponent-update function is important because it determines when a component doesn’t need to render.

Render and shouldComponentUpdate are also the only functions in the React lifecycle that require a return result. The result of the render function is used to construct the DOM object, and the shouldComponent-update function returns a Boolean that tells the React library whether the component should continue during the Update.

During the update process, the React library first calls shouldComponentUpdate. If this function returns true, the update process continues, followed by the render function. Otherwise, if you get a false, the update process stops immediately and no subsequent rendering is triggered.

ShouldComponentUpdate is important because if used properly, it can greatly improve the performance of React components. Although React rendering performance is already very good, no matter how fast rendering is, if it is found that there is no need to re-render, it can be faster.

We know that the render function should be a pure function whose logical inputs are the props and state of the component. So shouldComponentUpdate parameters are the props and state values that follow. If we want to define shouldComponentUpdate, we should use these two parameters, plus this.props and this.state to determine whether to return true or false.

If we add shouldCompomentUpdate to component function, it will continue to use all the React the default implementation of the components of the father React.Com ponent is the default implementation simply returns true, also is the need to render each update process. Of course, this is the safest way to do it. It’s wasteful at best, but you can’t go wrong. However, if we want to achieve higher performance, we should not be satisfied with the default implementation. We need to customize this function shouldComponentUpdate.

  1. ComponentWillUpdate and componentDidUpdate

If the component’s shouldComponentUpdate function returns true, React then calls the corresponding componentWillUpdate, Render, and componentDidUpdate functions in turn.

ComponentWillMount and componentDidMount, componentWillUpdate and ComponentDid-Update, the render function is sandwiched one after the other.

Unlike the loading process, when React is rendered on the server side, the Did function, known as componentDidUpdate, is not only executed on the browser side. It is called regardless of whether the update process occurs on the server side or the browser side.

Uninstall process

The React component uninstall process only involves a function componentWillUnmount. The React component is called before it is removed from the DOM tree, so this function is useful for some cleanup.

Unlike the loading and updating process, this function has no paired Did function, just one function, because it’s done after it’s unloaded, and there’s no “do it after it’s unloaded”.

However, the work is often related to componentDidMount componentWillUnmount, for example, in a way not React componentDidMount created some DOM elements, if no matter may lead to memory leaks, You need to clean up the created DOM elements in componentWillUnmount.