The React component lifecycle
What is React component lifecycle? You can think of the lifecycle as the different stages of a component from birth to death.
Three major phases of a component’s lifecycle
It is called before mounting the component into DOM.
It is the place where you initialize the local state and binds event methods.
The render method is the only required method in a class component. It should be noted that it is different from the ReactDOM.render().
Component.render() takes no arguments and returns the corresponding React element tree for the component. Component.render() is called when the component’s state or props change and shouldComponentUpdate() lifecycle method return true. It returns a new React element tree based on the changed state and props.
ReactDOM.render(element, container[, callback])
ReactDOM.render(), on the other side, takes a React element tree and a container DOM element as arguments. It turns the React element into corresponding DOM element and then mounting the DOM element into the container DOM element.
componentDidMount() will be invoked immediately after the component is mounted into a container DOM node.
Anythings that requires DOM nodes should be called there. For example, fetching data from a remote endpoint. Besides, you can call setState there, and the re-render will happen before the browser updates the screen cause some optimation of React. In other words, the user will only see one rendering even though setState() will trigger a re-render.
In the updating phase, any state or props changes will trigger a re-render. Other than that, it is no different than render() in the mounting phase.
componentDidUpdate(prevProps, prevState, snapshot)
componentDidupdate() is invoked immediately after updating occurs. However, it will not be called when initializing the component.
You can invoke network requests in this phase.
Also, you can use setState() in this phase. However, be careful to wrap setState() in a condition in order to avoid an infinite loop. The inner theory is obvious, a state change can cause React updating process, which will trigger the componentDidUpdate() again.
componentWillUnmount() will be invoked immediately before a component is unmounted. You should implement any unsubscribe actions there.
You can use ReactDOM.unmountComponentAtNode() to unmount a mounted component.