Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
November 8, 2020 08:31 am GMT

Lifecycle Methods: React

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 applications 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:
    • constructor()
    • static getDerivedStateFromProps()
    • render()
    • componentDidMount()
  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:
    • static getDerivedStateFromProps()
    • shouldComponentUpdate()
    • render()
    • getSnapshotBeforeUpdate()
    • componentDidUpdate()
  3. Unmount It is referred as "Death of the component." This method is called when a component is being removed from the DOM:
    • componentWillUnmount()

Mounting:

Constructor():

  • The constructor for a React component is called before it is mounted.
  • When implementing the constructor for a React.Component subclass, you should call super(props) before any other statement.
constructor(props) {  super(props);  this.state = { textChange: true };}
Enter fullscreen mode Exit fullscreen mode

static getDerivedStateFromProps():

  • getDerivedStateFromProps is one of those newly introduced lifecycle method replacing componentWillReceiveProps.
  • getDerivedStateFromProps is used in some rare cases where state depends on the change of props.
  • getDerivedStateFromProps is a static method. So it does not have access to component instance this. It has only updated props and current state object.
  • If you need to do anything after state update like fetching data, then you should use componentDidUpdate lifecycle method.
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;  }
Enter fullscreen mode Exit fullscreen mode

render():

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

componentDidMount():

  • componentDidUpdate() is invoked immediately after updating occurs. This method is not called for the initial render.
  • 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.
  • 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.
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;
Enter fullscreen mode Exit fullscreen mode

Update:

shouldComponentUpdate():

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

getSnapshotBeforeUpdate():

  • getSnapshotBeforeUpdate(prevProps, prevState) is invoked after render() method but just before DOM is changed.
  • That means before virtual DOM is converted to actual DOM ( known as pre-commit phase ), this method is called.
getSnapshotBeforeUpdate(prevProps, prevState) {    if (prevProps.list.length < this.props.list.length) {      const list = this.listRef.current;      return list.scrollHeight - list.scrollTop;    }    return null;  }
Enter fullscreen mode Exit fullscreen mode

render():

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

componentDidUpdate():

  • componentDidUpdate() is invoked immediately after updating occurs. This method is not called for the initial render.
  • componentDidUpdate() takes as its first two arguments the previous props and the previous state.
  • Inside the method we can check if a condition is met and perform an action based on it.
componentDidUpdate(prevProps) {  if (this.props.userID !== prevProps.userID) {    this.fetchData(this.props.userID);  }}
Enter fullscreen mode Exit fullscreen mode

Unmount:

componentWillUnmount():

  • componentWillUnmount is the last function to be called immediately before the component is removed from the DOM.
  • componentWillUnmount() is generally used to perform clean-up for any DOM-elements or timers created in componentWillMount
   componentWillUnmount() {        document.removeEventListener("click", this.closeMenu);    }
Enter fullscreen mode Exit fullscreen mode

Original Link: https://dev.to/viraj/lifecycle-methods-react-41j2

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To