Lifecycle Methods: React 🚀
Tags: react, webdev, beginners
Published: 2020-11-08 08:31:04

###**What is React?**
React is the most popular front-end JavaScript library in the field of web development.
React is created for building fast and interactive user interfaces for web and mobile applications. 
It is an open-source, component-based, front-end library responsible only for the application’s view layer.
It is used by large, established companies like Netflix, Airbnb, Instagram etc.

###**What is React.js?**
React.js often referred to as React or ReactJS is a JavaScript library responsible for building a hierarchy of UI components.
It provides support for both frontend and server-side.

###**What is React-Native?**
React Native is a framework for building native applications using JavaScript. 
React Native compiles to native app components, which makes it possible for you to build native mobile applications.

#####**In simple words, you can build web applications or websites using using react.js and on the other hand you can build only mobile applications using react-native.**

###**What are React lifecycle methods?**
Every component in React goes through a lifecycle of events. 
Just like human beings components go through a cycle of birth, growth, and death.

1. Mounting – It is referred as "Birth of the component".
These methods are called in the following order when an instance of a component is being created and inserted into the DOM:
<ul>
<li>constructor()</li>
<li>static getDerivedStateFromProps()</li>
<li>render()</li>
<li>componentDidMount()</li>
</ul>
2. Update – It is referred as "Growth of the component." An update can be caused by changes to props or state. These methods are called in the following order when a component is being re-rendered:
<ul>
<li>static getDerivedStateFromProps()</li>
<li>shouldComponentUpdate()</li>
<li>render()</li>
<li>getSnapshotBeforeUpdate()</li>
<li>componentDidUpdate()</li>
</ul>
3. Unmount – It is referred as "Death of the component." This method is called when a component is being removed from the DOM:
<ul>
<li>componentWillUnmount()
</li>
</ul>


####**Mounting:**
> Constructor():
<ul>
<li>The constructor for a React component is called before it is mounted.</li>
<li>When implementing the constructor for a React.Component subclass, you should call super(props) before any other statement.</li>
```
constructor(props) {
  super(props);
  this.state = { textChange: true };
}
```
</ul>
***


> static getDerivedStateFromProps():
<ul>
<li>getDerivedStateFromProps is one of those newly introduced lifecycle method replacing componentWillReceiveProps.</li>
<li>getDerivedStateFromProps is used in some rare cases where state depends on the change of props.</li>
<li>getDerivedStateFromProps is a static method. So it does not have access to component instance this. It has only updated props and current state object.</li>
<li>If you need to do anything after state update like fetching data, then you should use componentDidUpdate lifecycle method.</li>
```
static getDerivedStateFromProps(nextProps, prevState){
   if(nextProps.someValue!==prevState.someValue){
     return { someState: nextProps.someValue};
  }
  else return null;
}

// This is an example of how to fetch external data in response to updated props:
  static getDerivedStateFromProps(nextProps, prevState) {stuff).
    if (nextProps.id !== prevState.prevId) {
      return {
        externalData: null,
        prevId: nextProps.id
      };
    }
    return null;
  }
```
</ul>
***

> render():
<ul>
<li>React renders HTML to the web page by using a function called ReactDOM.render()</li>
<li>The ReactDOM.render() function takes two arguments, HTML code and an HTML element.</li>
<li>The purpose of the function is to display the specified HTML code inside the specified HTML element.</li>
```
import React, { Component } from 'react';
class App extends Component {
  render() {
    return (
      <div>
          <h1 className="react"> React render()</h1>
      </div>
    );
  }
}
export default App;
```
</ul>
***

> componentDidMount():
<ul>
<li>componentDidUpdate() is invoked immediately after updating occurs. This method is not called for the initial render.</li>
<li>componentDidMount() method is the perfect place, where we can call the setState() method to change the state of our application and render() the updated data loaded JSX.</li>
<li>this technique called by React itself to either fetch the data from An External API or perform some unique operations which need the JSX elements.</li>
```
import React, { Component } from 'react';

class App extends Component {

  constructor(props){
    super(props);
    this.state = {
      data: 'Viraj Nimbalkar'
    }
  }

  getData(){
    setTimeout(() => {
      console.log('Our data is fetched');
      this.setState({
        data: 'Hello Developers!!'
      })
    }, 1000)
  }

  componentDidMount(){
    this.getData();
  }

  render() {
    return(
      <div>
      {this.state.data}
    </div>
    )
  }
}

export default App;
```
</ul>
***



####**Update:**
> shouldComponentUpdate():
<ul>
<li>shouldComponentUpdate() allows your Component to exit the Update life cycle if there is no reason to apply a new render.</li>
<li>This method only exists as a performance optimization.</li>
<li>shouldComponentUpdate() is a no-op that returns true. This means every time we start an Update in a Component, we will re-render.</li>
```
class ListItem extends Component {
    shouldComponentUpdate(nextProps, nextState) {
        return nextProps.isFavourite != this.props.isFavourite;
    }
    ...
}
```
</ul>
***


> getSnapshotBeforeUpdate():
<ul>
<li>getSnapshotBeforeUpdate(prevProps, prevState) is invoked after render() method but just before DOM is changed.</li>
<li>That means before virtual DOM is converted to actual DOM ( known as pre-commit phase ), this method is called.</li>
```
getSnapshotBeforeUpdate(prevProps, prevState) {
    if (prevProps.list.length < this.props.list.length) {
      const list = this.listRef.current;
      return list.scrollHeight - list.scrollTop;
    }
    return null;
  }
```
</ul>
***

> render():
<ul>
<li>React renders HTML to the web page by using a function called ReactDOM.render()</li>
<li>The ReactDOM.render() function takes two arguments, HTML code and an HTML element.</li>
<li>The purpose of the function is to display the specified HTML code inside the specified HTML element.</li>
```
import React, { Component } from 'react';
class App extends Component {
  render() {
    return (
      <div>
          <h1 className="react"> React render()</h1>
      </div>
    );
  }
}
export default App;
```
</ul>
***

> componentDidUpdate():
<ul>
<li>componentDidUpdate() is invoked immediately after updating occurs. This method is not called for the initial render.</li>
<li> componentDidUpdate() takes as its first two arguments the previous props and the previous state.</li>
<li>Inside the method we can check if a condition is met and perform an action based on it.</li>
```
componentDidUpdate(prevProps) {
  if (this.props.userID !== prevProps.userID) {
    this.fetchData(this.props.userID);
  }
}
```
</ul>
***

####**Unmount:**
> componentWillUnmount():
<ul>
<li>componentWillUnmount is the last function to be called immediately before the component is removed from the DOM.</li>
<li>componentWillUnmount() is generally used to perform clean-up for any DOM-elements or timers created in componentWillMount </li>
```
   componentWillUnmount() {
        document.removeEventListener("click", this.closeMenu);
    }
```
</ul>
***