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.

https://projects.wojtekmaj.pl/react-lifecycle-methods-diagram/

Three major phases of a component’s lifecycle

constructor

It is called before mounting the component into DOM.

It is the place where you initialize the local state and binds event methods.

render()

The render method is the only required method in a class component. It should be noted that it is different from the ReactDOM.render().

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()

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.

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()

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()

componentWillUnmount() will be invoked immediately before a component is unmounted. You should implement any unsubscribe actions there.

ReactDOM.unmountComponentAtNode(container)

You can use ReactDOM.unmountComponentAtNode() to unmount a mounted component.

A front-end developer who likes designing stuffs. Technical blog rookie. Loving sharing.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store