Journey of ReactJS Component’s Life Cycle

React is a declarative, efficient, and flexible JavaScript library for building user interfaces. We can create complex UI’s from small code called “Components”. All we know that our UI made of small components. for example-Sidenavbar,Header,Footer, Button, all are known as component.

In Universe all objects cross some step like birth,grow.. then destroy. same happen with our react components. these step known as Life cycle. life cycle method play vital role in react application devlopment.so we have to clear understanding of these life cycle methods. below i will mention some important methods that is really useful..

Every react components have 4 phases

(1) Initialization (2) Mounting (3) Updation (4) Unmounting

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

Initialization:In this phase the React component setting up the initial states. we can also set our initial state through props also

class Post extends React.Component {
constructor(props) {
super(props)
this.state = {
name:"Shekhar",
postData:""
}
}

The component is setting up the initial state in the constructor, which can be changed later by using thesetState method.

Mounting:: After preparing with initial data state and props, our React Component is ready to mount in the browser DOM. This phase gives hook methods for before and after mounting of components. The methods which gets called in this phase are — -

  • componentWillMount is executed just before the React Component is about to mount on the DOM.All the things that you want to do before a component mounts has to be defined here.
    This method is executed once in a lifecycle of a component and before first render. there is a huge debate going on this method. right now react 16.3 it is deprecated. u can read abou from here
  • render mounts the component onto the browser. This is a pure method, which means it gives the same output every time the same input is provided. according to react docs
if you need to interact with the browser, perform your work in componentDidMount() or the other lifecycle methods instead. Keeping render() pure makes components easier to think about...
  • componentDidMount this is the hook method which is executed after the component did mount on the dom. 
    This method is executed once in a lifecycle of a component and after the first render.
     in this method, we can access the DOM, we should make any ajax call in this method. this is the best place for calling api. below is my code i am calling api and update my state.
componentDidMount() {
let postId = this.props.match.params.id
PostAPI.getPostData(postId)
.catch(error => console.error('Error:', error))
.then(response => {
if (response.returnVal) {
this.setState({
postData: response.returnVal
})
}
})
}
  • Updation: in this phase component’s state updated by calling setState method or sending new props. means if we get data from our database then we update our state this is known as updation phase. in this phase the methods are —
  • shouldComponentUpdate: tells the React that when the component receives new props or state is being updated, should React re-render or it can skip rendering? 
    by the name of method it is clear what this method perform should the Component be Updated? 
    Hence this method should return true or false, and accordingly the component would be re-rendered or skipped. By default, this method return true. if this method return false then component not re render again. for optimization purpose we used this method for preventing unnesseary render.below i have mention code in that code we checked our previous state is same as new state if name is not equal means state has been updated means we have to show new name on dom so we return true. if it return true means component again render.
shouldComponentUpdate(nextProps, nextState)
{
if(this.state.name !== nextState.name)
return true;
}
  • componentWillUpdate is executed when shouldComponentUpdatereturns true.this method is similar to componentWillMount or constructor.
    means whatever we perform before first render same we can perform here. means we can decide what we want to show ater first render in this method. we can prepare for that.

note:::this method is now changed into UNSAFE_componentWillUpdate() in react 16.3

  • render After componentWillUpdate render method is called.
  • componentDidUpdate is invoked immediately after updating occurs. This method is not called for the initial render.

Use this as an opportunity to operate on the DOM when the component has been updated. This is also a good place to do ajax requests.

componentDidUpdate() will not be invoked if shouldComponentUpdate() returns false.

componentDidUpdate(prevProps) {
// Typical usage (don't forget to compare props):
if (this.props.postId !== prevProps.postId) {
//we can ajax call here//
}
}

Unmounting:

In this phase, the component will get unmounted from the DOM. The method which is called in this phase

  • componentWillUnmount This method is the last method in the lifecycle. This is executed just before the component gets removed from the DOM.
    componentWillUnmount() is invoked immediately before a component is unmounted and destroyed. Perform any necessary cleanup in this method, such as invalidating timers, canceling network requests, or cleaning up any subscriptions that were created in componentDidMount().

Note — ->We should not call setState() in componentWillUnmount() because the component will never be re-rendered. Once a component instance is unmounted, it will never be mounted again. below i am clear my redux store data with the dispatchng with blank postdata.

componentWillUnmount() {
let PostData = {
post: [],
}
updatePost(this.props.dispatch, PostData)
}

Order Of Calling Lifecycle Methods

  Constructor()
componentWillmount()
render()
child component(if we called child componnet)
componentDidMount()
shouldComponentUpdate()
componentWillUpdate() only when shouldcomponnet return true
render()
componentDidUpdate()
componentWillUnmount()

This is my first blog i hope this blog helps you. if u feel realy it helps you then please like and comment. your comment and like give me a confidence then i will make another blog very soon. if you have any question you can also mail me on

shekharmishra.krish@gmail.com

thanku so much