What are Component Lifecycle Methods in React

The lifecycle of a component in React starts when this component mounts and renders to the DOM for the first time. If it is already mounted it can render again if it needs to change its appearance or content after an update of its props or state. The lifecycle is ended when the component is removed from the DOM and it won’t be mounted again.

Components in React can be defined as classes or functions. Defining components as classes provides more features such as the availability of lifecycle methods. Overriding these methods allows you to run your code at particular times during the process. So React offers and supports methods for each phase in the component lifecycle: mounting, updating, and unmounting.

In this article we will discuss the most useful React lifecycle methods that you should know and use only when you must because they add complexity to your application. Except the render() method, which is a required method in the component definition. And show you when and how to use them with examples.

Component Lifecycle Methods in React

A React component goes through three phases during its lifecycle, and each phase has its own methods:

Phase1: Component Mounting lifecycle methods

Mounting in React means or represents the process of converting the virtual components into actual DOM elements. React supports four mounting lifecycle methods for component classes: constructor(), which is called first, then static getDerivedStateFromProps() which is rarely used, followed by render(), and finally componentDidMount().

constructor()

constructor() method is used to initialize the local state of your component using this.state and to bind the event handler methods defined within the component. It is the first method that gets called before the other mounting methods and takes props as an argument.

To inherit methods from React.Component and initiate the constructor method, you should start your constructor method by calling the super(props). Note that Constructor method is the only place where you can assign a value to this.state directly. Outside this method, you must use this.setState instead.

// constructor() method example

class ComponentExample extends React.Component {
  
constructor(props) {
  super(props);
  this.state = { showForm : false };
  this.handleClick = this.handleClick.bind(this);
}

 handleClick=()=>{
    this.setState({showForm : true});
}

}


static getDerivedStateFromProps()

As mentioned in introducing this article, static getDerivedStateFromProps() method is rarely used. The React team introduced this method as an alternative to the componentWillReceiveProps().

static getDerivedStateFromProps() gets fired every time a component is rendered, just before render() method, which is sometime unnecessarily. This lifecycle method is used when the component state depends on changes in its props, such as in transition components. This method takes two parameters (props, state). It returns an object to update the component state in case of prop changes and returns null if there is no change.

// static getDerivedStateFromProps() method example

class ComponentExample extends React.Component {
  
constructor(props) {
  super(props);
  this.state = { showForm : false };
  
}

 

static getDerivedStateFromProps(props, state) {
    if (props.showForm === true) {
//props.showForm was defined by by the component caller of this component.
      return { showForm : props.ShowForm};
    } else {
    return null;
  }
}

}



render()

render() is the only method required to define and mount a component class. It returns JSX elements, children components or nothing in case of return {condition && <ChildComponent />} pattern, and inserts them into the DOM tree.

To keep the render pure without side-effects, we cannot change the component state using setState in it. Being pure allows this method to render the same result each time it is fired with the same this.props and this.state.

// render() method example

class ComponentExample extends React.Component {
  
constructor(props) {
  super(props);
  this.state = { showForm : false };
  this.handleClick = this.handleClick.bind(this);
}

 handleClick=()=>{
    this.setState({showForm : true});
}



render(){
      return (
        <div>
             <div >
              <h3> Click here to see the Form </h3>
              <Button onClick = {this.handleClick}>ADD NEW</Button>
            </div>
            <div >
              {this.state.showForm && <FormComponent />}
            </div>
      </div>
    );
   }



}



componentDidMount()

componentDidMount() is the most used lifecycle method. It is called only once, just after the first render of the component, that makes it a good place for DOM manipulation, fetching requests for loading initial data from endpoints and setting up intervals using the setInterval and setTimeout functions. We can also use the setState() to update the component state, which causes an extra render, but the user won’t notice that.

// componentDidMount() method example

class ComponentExample extends React.Component {
  
constructor(props) {
  super(props);
  this.state = {
       showForm : false,
       elements : []
 };
  
}

componentDidMount(){
        
      Axios.get('/api/elements')
     .then(res => {
         if(res.data.elements){
             this.setState({elements: res.data.elements});

         } else{
         alert(res.data.message);
         }
     });
   
   setTimeout(() => {
      this.setState({showForm : true})
    }, 2000);

    }

}



Phase2: Component Updating lifecycle methods

Commonly used lifecycle methods when a component is updated are :

  • render(): since the component will mount again after changing its props and state.
  • static getDerivedStateFromProps(): this method gets fired every time a component is rendered after a parent component was updated and is passing down the same props to its children.
  • componentDidUpdate(): more details in the following section.

componentDidUpdate()

  • This method is used to update the DOM just after changes to props or state happen.
  • It can take two parameters (prevProps, prevState) and it is the last place where the previous props and the previous states are available.
  • You can access props and state through this.props and this.state
  • When calling setState() within componentDidUpdate, you must wrap it in a condition to check the state or props changes from previous state and previous props in order to prevent an infinite loop.
// componentDidUpdate() method example

class ComponentExample extends React.Component {
  
constructor(props) {
  super(props);
  this.state = {
       userInfo : {}
 };
  
}

componentDidUpdate(prevState){
  // In case user informations have not changed, we won't make an api call.
  if (this.state.userInfo !== prevState.userInfo) { 
      Axios.get('/api/users/${id}')
     .then(res => {
         if(res.data.user){
             this.setState({userInfo: res.data.user});

         } else{
         alert(res.data.message);
         }
     });
   
    }
}

}


Phase3: Component Unmounting lifecycle methods

Unmounting a component means remove it from the DOM and not mount it again. So in applications with many components, it’s very important to free up resources taken by the components when they are destroyed.

componentWillUnmount()

The componentWillUnmount method is called right before the component is removed from the DOM. This method is the perfect spot to invalidate and end intervals, to cancel api calls and cleanup the subscriptions created in componentDidMount().

We can not use setState() in componentWillUnmount() because the component is destroyed and will never be mounted again.

// componentWillUnmount() method example
// In this example ComponentExample is the parent component.

class ComponentExample extends React.Component {
  
constructor(props) {
  super(props);
  this.state = { showWelcomeMessage : true };
  this.handleClick = this.handleClick.bind(this);
}

 handleClick=()=>{
    this.setState({showWelcomeMessage : false});
}



render(){
      return (
        <div>
             <div >
              {this.state.showWelcomeMessage && <WelcomeComponent />}
            </div>
             <div >
              <h3> Click here to hide the welcome message </h3>
              <Button onClick = {this.handleClick}>HIDE WELCOME MESSAGE</Button>
            </div>
            
      </div>
    );
   }
}

// WelcomeComponent is the child component.

class WelcomeComponent extends React.Component {
  componentWillUnmount() {
    alert("The welcome message is about to be removed.");
    // here we can cancel all the api calls made by this component and end intervals.
   
  }
  render() {
    return (
      <h1>WELCOME !!</h1>
    );
  }
}

NOTE:

In this article we selected for you the commonly used lifecycle methods that will help you understand the DOM behavior. If you want to know more about the other lifecycle methods a documentation is available here React website website and for a detailed diagram click here Lifecycle Methods Diagram. But note that most of them are rarely used and some are unsafe to use, and they risk to be deprecated in the future versions of React.

Translate »