ITZone

[Basic] Life cycle of Component in Reactjs

Today I will introduce the basic lifecycle of components in reactjs, including what stages and what functions will each phase call?

Hope to discuss with you guys.

What is life cycle? It is the life cycle of an object from birth, growth to death.

Note: Life cycles in this tutorial for class components, understanding life cycle is very important to understand how reactjs components work.

1. Definition:

The life cycle of a component in reactjs is the process from creating, modifying, and destroying a component.

Consists of 3 stages:

Mounting

Updating

UnMounting

Looking at the diagram above we will know when Component

Next I will introduce some commonly used functions: Constructor, render, DidMount, WillUnmount, DidUpdate

2. Constructor

When component mouting (created) will go through the Constructor . function

In the constructor will declare the state, the properties (properties) of the component.

Note:  super(props) to call the constructor of the parent React.Component component that the child Component inherits from.

3. DidMount()

Like the example below: call the api to get the comment content and then setState to render it again. (now there is comment content taken from api)

Note The DidMount() function only runs once when the component is created.

4. WillUnMount()

When component unmounting (cancellation) we will call the function WillUnMount(). When we don’t render the component or turn the page, the component will be destroyed to render the new content. Used to cancel timeout, clearInterval. (if not canceled, it will run continuously), reset data if necessary.

Note: the WillUnMount() function only runs once when the component is in the component’s lifecycle. Similarly, Mount() only runs once. And DidUpdate() can be called multiple times if there are multiple updates

4. DidUpdate()

Note:   Be careful when using DidUpdate() to strictly manage the changes of props, state. If you are not careful, there is a possibility that it will be rendered many times, causing the program to slow down. There are even cases of endless looping due to state changes inside DidUpdate() function.

Refer :

https://www.tutorialspoint.com/reactjs/reactjs_component_life_cycle.htm https://reactjs.org/docs/state-and-lifecycle.html

Share the news now