Home >> Tutorials >> React Component Lifecycle Methods
Previous Page

React Components

Lifecycle methods are various methods which are invoked at different phases of the lifecycle of a component.
React Component Lifecycle Phases (Updated as Version 16.8):

The React js component goes through the following phases which are given below:

  1. Mounting Phase:

    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()

    Note: Following methods are considered legacy and you should avoid this:

    • UNSAFE_componentWillMount()
  2. Updating Phase:

    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:

    Updation is the process that occurs when a component’s state or properties(props) get updated.
    • static getDerivedStateFromProps()
    • shouldComponentUpdate()
    • render()
    • getSnapshotBeforeUpdate()
    • componentDidUpdate()

    Note: Following methods are considered legacy and you should avoid these:

    • UNSAFE_componentWillUpdate()
    • UNSAFE_componentWillReceiveProps()
  3. Unmounting Phase:

    This method is called when a component is being removed from the DOM:

    Unmounting is the process that occurs when a component is unmounted from the DOM.
    • componentWillUnmount()
You may also like - Node Js Interview Questions
Most Commonly Used Lifecycle Methods:
  • render()
  • constructor()
  • componentDidMount()
  • componentDidUpdate()
  • componentWillUnmount()
Rarely Used Lifecycle Methods:
  • shouldComponentUpdate()
  • static getDerivedStateFromProps()
  • getSnapshotBeforeUpdate()
Let's discuss in details: Lifecycle Methods
  1. constructor():

    This is the first method that gets called whenever a component is created. The constructor is called only once in the complete lifecycle of a component. It's used to set up the initial values of variables(props) and component state(state).

    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.
    import React, { Component } from 'react';
    class myComponent extends Component{
    constructor(props) {
      super(props);
      // Don't call this.setState() here!
      this.state = { counter: 0 };
      this.handleClick = this.handleClick.bind(this);
    }
    }
    

    Constructor is the only place where you should assign this.state directly. In all other methods, you need to use this.setState() instead.

  2. static getDerivedStateFromProps(nextProps, prevState)
    class Example extends React.Component {
    static getDerivedStateFromProps(props, state) {
    // ...
    }
    }
    

    The new static getDerivedStateFromProps lifecycle is invoked after a component is instantiated as well as when it receives new props.

    It can return an object to update state, or null to indicate that the new props do not require any state update

    Together with componentDidUpdate, this new lifecycle should cover all use cases for the legacy componentWillReceiveProps.

  3. render():
    • render() is the most widely used method in react lifecycle.
    • render() method called by default because it needs to display the HTML markup or we can say JSX syntax.
    import React, { Component } from 'react';
    class App extends Component {
    render() {
    return (
    	

    Welcome to React component lifecycle methods!

    ); } } export default App;
    Q:- We can not define setState() inside render() method why?

    Reason:- setState() function changes the state of the application and causing a change in the state called the render() function again. So if you write something like this then calling the function stack will go for infinity and application gets the crash.

  4. componentDidMount():

    This method gets called immediately after the component did mount in the DOM.

    import React, { Component } from 'react';
    class myComponent extends Component {
    constructor(props) {
    super(props);
    this.state = {
    	name: 'Full Stack Tutorials',
    	website: 'https://www.fullstacktutorials.com'
    }
    }
    getMyData(){
    this.setState({
    datalist: {
    	name: 'ReactJs Lifecycle Methods',
    	website: 'https://reactjs.org'
    }
    });
    }
    componentDidMount(){
    this.getMyData();
    }
    render() {
    return(
    	

    Website Name: {this.state.datalist.name}

    Website Url: {this.state.datalist.website}

    ) } } export default myComponent;

    You may call setState() immediately in componentDidMount()

    Q:- Where in the component lifecycle should I make an AJAX call?

    According to official React docs, the recommended place to do Ajax requests is in componentDidMount

  5. shouldComponentUpdate():

    it should return true or false value. This will determine if the component will be updated or not. This is set to true by default. If you are sure that the component doesn't need to render after state or props are updated, you can return false value.

  6. getSnapshotBeforeUpdate(prevProps, prevState)
    class Example extends React.Component {
    getSnapshotBeforeUpdate(prevProps, prevState) {
    // ...
    }
    }
    

    The new getSnapshotBeforeUpdate lifecycle is called right before mutations are made (e.g. before the DOM is updated). The return value for this lifecycle will be passed as the third parameter to componentDidUpdate. (This lifecycle isn’t often needed, but can be useful in cases like manually preserving scroll position during rerenders.)

    Together with componentDidUpdate, this new lifecycle should cover all use cases for the legacy componentWillUpdate.

  7. componentDidUpdate():

    componentDidUpdate() is invoked immediately after updating occurs. This method is not called for the initial render.

    componentDidUpdate(prevProps, prevState, snapshot)
    
    componentDidUpdate(prevProps) {
    // Typical usage (don't forget to compare props):
    if (this.props.userID !== prevProps.userID) {
    this.fetchData(this.props.userID);
    }
    }
    

    You may call setState() immediately in componentDidUpdate() but note that it must be wrapped in a condition like in the example above, or you'll cause an infinite loop

    Note:

    • If your component implements the getSnapshotBeforeUpdate() lifecycle (which is rare), the value it returns will be passed as a third "snapshot" parameter to componentDidUpdate(). Otherwise this parameter will be undefined.
    • componentDidUpdate() will not be invoked if shouldComponentUpdate() returns false.
  8. componentWillUnmount():

    componentWillUnmount() is invoked immediately before a component is unmounted and destroyed. this is last method of React Component Lifecycle.

    You 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.

Previous Page

React Components