20 - React Component Life Cycle Methods(Important)

React Component Life Cycle Methods
The series of events that happens from mounting to unmounting of a React component.

OR

Each component in React has a lifecycle which you can monitor and manipulate during its three main phases.



PHASES OF REACT  LIFE CYCLE

The three phases are: Mounting, Updating, and Unmounting.


Mounting (Birth of your component) :

Mounting means putting elements into the DOM.



Updating (Growth of your component) :

The next phase in the lifecycle is when a component is updated.

A component is updated whenever there is a change in the component's state or props.




Unmounting (Death of your component) :

The next phase in the lifecycle is when a component is removed from the DOM, or unmounting as React likes to call it.




Important methods in React Component Cycle

render() method
componentDidMount() method
componentDidUpdate() method
componentWillUnmount() method


Explain methods in React Component Cycle briefly


render() method:
The render() method is of course called when a component gets updated, it has to re-render the HTML to the DOM, with the new changes.

Basically, It is used to render the HTML.It is used to render DOM while using class based component. 




componentDidMount() method:
The componentDidMount() method is called after the component is rendered.
This is where you run statements that requires that the component is already placed in the DOM.

We can use setState , async and await methods in componentDidMount() method.




componentDidUpdate() method:
The componentDidUpdate method is called after the component is updated in the DOM.




componentWillUnmount() method
The componentWillUnmount method is called when the component is about to be removed from the DOM.
It is usually used to perform cleanups.



 Sequence of method run while mounting, update and unmounting the React component

(1) While mounting

--> "constructor" runs after "render" method is invoked.
--> Updating the DOM.
--> componentDidMount() method will be executed



(2) While Updating

   Three possible ways to update React class component are:
-->New props
-->using setState
-->using forceUpdate

After updating
--> render() method executed at start
--> React updates the "DOM and references"
--> componentDidUpdate() method will run.




(3) While Unmounting
--> componentWillMount() method will be executed.
--> Component will be unmounted.



Image 1 -  React Life Cycle  Diagram 

Comments

Popular posts from this blog