Lifecycle methods in React 16

    Oct 05, 2019       by Suraj Roy
react16-lifecycle-methods.jpg

React.js is the most popular front-end javascript library used today for single-page web applications today. It's a JavaScript library by Facebook with 155k start on Github. It allows developers to create large web applications that can change data, without reloading the page. The main purpose of React is to be fast, scalable, and simple.

If you have started working on React.js then you must have used a few common lifecycle methods while creating the applications. For an experienced React developer, it's necessary to have an understanding of the complete life cycle methods. In this article, you will see the lifecycle methods of React.js.

If we analyse the running a web page on the browser then it has below steps under which it goes:

  • before page render
  • while page render
  • listening for change to the properties
  • finish rendering

React or Angular both have their life cycle methods

In this article, I will brief the React lifecycle methods(with example) in the order they are called by React in the DOM.

React lifecycle methods

1. constructor()

In class-based React component, constructor() is the very first method() which is called while loading the component. The constructor takes the props(object) as an argument and parent class is called using super() for accessing this.props to props inside the class. It is the only place where you can assign this.state directly, In other methods you need this.setState() instead.

 

class FirstComponent extends Component {

  constructor(props) {

    super(props);

    this.state = {

      counter: 0

    };

  }

}

 

Typically, in React constructors are only used for two purposes:

  • Initializing local state by assigning an object to this.state.
  • Binding event handler methods to an instance.

Note: If you don’t need to initialize state and methods binding, you don’t need to use a constructor for your React component.

 

2. getDerivedStateFromProps()

This is called just after calling the constructor and before calling the render method. It should return an object to update the state, or null to update nothing. We don't commonly use this method while creating apps in React. It is a static method so this cannot be used inside it.

static getDerivedStateFromProps(props, state) {

  return null;

}

 

It can also be placed inside the constructor method and  called on every render.

3. render()

This method is the only required method in React class component. All the needed JSX(whole work needed to show over UI) is written inside this method. 

render(){

  return <div>Hello world!</div>

}

 

4. componentDidMount()

This methods is called just after render method as soon as component is mounted. It is adviced to set up any subscription  in this method. If anyting subscribed here, don’t miss to unsubscribe under componentWillUnmount().

componentDidMount() {

   // .... componentDidMount called here

}

 

5. shouldComponentUpdate()

This method is called just after the componentDidMount method, this method does not allow us to set the state in it. Use shouldComponentUpdate() to let React know if a component’s output is not affected by the current change in state or props. The default behavior is to re-render on every state change, and in the vast majority of cases you should rely on the default behavior. It returns a boolean, default true.

shouldComponentUpdate(nextProps, nextState) {

//should component update called here

return nextState.users.length < this.state.users.length;

}

 

6. getSnapshotBeforeUpdate()

It is one of the most frequent lifecycle method used.  As the name suggests, It is called between the component is rendered and when it is updated in DOM. Any value returned by this lifecycle will be passed as a parameter to componentDidUpdate().

getSnapshotBeforeUpdate(prevProps, prevState){

  if (prevState.users.length < this.state.users.length) {

    return { this.state.users };

  }

  return null;

}

 

7. componentDidUpdate()

This method is called just after the getSnapshotBeforeUpdate, just after the DOM update.

componentDidUpdate(prevProps, prevState, snapshot) {

  if (snapshot.users) {

    return <div> Users available! </div>

  }

}

 

8. componentWillUnmount()

This method is invoked just before a component is unmounted and destroyed. It performs any necessary cleanup in this method, such as invalidating timers, canceling network requests, or cleaning up any subscriptions that were created in componentDidMount().

componentWillUnmount(){

  window.removeEventListener("restart");

}

 

9. getDerivedStateFromError()

This lifecycle is invoked after an error has been thrown by a descendant component. It receives the error that was thrown as a parameter and should return a value to update state.

 

class ErrorBoundary extends React.Component {

  constructor(props) {

    super(props);

    this.state = { hasError: false };

  }

 

  static getDerivedStateFromError(error) {

    // Update state so the next render will show the fallback UI.

    return { hasError: true };

  }

 

  render() {

    if (this.state.hasError) {

      return <h1>Something went wrong.</h1>;

    }

 

    return this.props.children;

  }

}

 

10. componentDidCatch()

 

This lifecycle is invoked after an error has been thrown by a descendant component. It receives two parameters:

  1. error - The error that was thrown.
  2. info - An object with a componentStack key containing information about which component threw the error.

componentDidCatch(error, info) {

  console.log(info.componentStack);

}

 

Conclusion

In this article, We have gone through the different lifecycle methods of React 16. If you want to get a more depth understanding of the lifecycle methods click here.

I hope this article helped you. You can also find other demos of React.js Sample Projects here to start working on enterprise-level applications.

Let me know your thoughts over email demo.jsonworld@gmail.com. I would love to hear them and If you like this article, share it with your friends.

Thank You!


WHAT'S NEW

Find other similar Articles here: