ReactJS | Component Life Cycle

ReactJS Component Life Cycle

In this blog, we will learn about the Lifecycle of Components in ReactJS. 

We have already learned about the Components of ReactJS. Today I will describe the Lifecycle of components in ReactJS. So let’s get started.

Component Lifecycle in ReactJS

In simple terms, the Lifecycle of a component can be referred to as the birth, growth, and death of a component. In ReactJS, every component has its own lifecycle which involves various methods. These lifecycle methods are called at various points during a component’s life. Each component in ReactJS has four main phases during its lifecycle.

The four phases are: Initialization, Mounting, Updating, and Unmounting.

Initialization

It is the start phase of the lifecycle of the ReactJs component. The component starts with the DOM, and contains the default Props and initial State. This default property is done in the constructor of a component. The initial phase only occurs once.

  • getDefaultProps() – It is used to specify the default value of this.props. It is invoked before the creation of the component or any props from the parent are passed into it.
  • getInitialState() – It is used to specify the default value of this.state. It is invoked before the creation of the component.

Mounting 

The mounting phase occurs when the elements are created and inserted into the DOM. React has four built-in methods that get called, in this order, when mounting a component:

  1. constructor()
  2. getDererivedStateFromProps()
  3. render()
  4. componentDidMount()

The render() method is required and will always be called; the others are optional and will be called if you define them.

constructor 

The constructor() method is called when the component is initiated, and it is the natural place to set up the initial state and other initial values. The constructor() method is called with the props, as arguments, and you should always start by calling the super(props) before anything else; this will initiate the parent’s constructor method and allow the component to inherit methods from its parent (React.Component).

class Header extends React.Component
{
    constructor(props)
    {
        super(props);
        this.state = {favGame: "Cricket"};
    }
    render()
    {
        return (
          <h1>My Favorite Color is {this.state.favGame}</h1>
        );
    }
}
ReactDOM.render(<Header />,
document.getElementById(‘root'));

getDerivedStateFromProps 

The getDerivedStateFromProps() method is called right before rendering the element(s) in the DOM. This is the natural place to set the state object based on the initial props. It takes the state as an argument and returns an object with changes to the state. The example below starts with the favorite color being “red”, but the getDerivedStateFromProps() method updates the favorite color based on the favcol attribute:

class Header extends React.Component
{
    constructor(props)
    {
        super(props);
        this.state = {favoriteGame: "red"};
    }
    static getDerivedStateFromProps(props, state)
    {
        return {favoriteGame: props.favGame };
    }
    render()
    {
        return (
          <h1>My Favorite Color is {this.state.favoriteGame}</h1>
        );
    }
}
ReactDOM.render(<Header favGame="yellow"/>,
document.getElementById('root'));

Render

The render() method is required and is the method that actually outputs the HTML to the DOM.

class Header extends React.Component
{
    render()
    {
        return (
          <h1>This is the content of the Header component</h1>
        );
    }
}
ReactDOM.render(<Header />, document.getElementById('root'));

ComponentDidMount

The componentDidMount() method is called after the component is rendered. This is where you run statements that require that the component is already placed in the DOM.

class Header extends React.Component
{
    constructor(props)
    {
        super(props);
        this.state = {favoritecolor: "red"};
    }
    componentDidMount()
    {
        setTimeout(() => {
            this.setState({favoritecolor: "yellow"})
        }, 1000)
    }
    render()
    {
        return (
          <h1>My Favorite Color is {this.state.favoritecolor}</h1>
        );
    }
}
ReactDOM.render(<Header />, document.getElementById('root'));

Updating

Here a component is updated whenever there is a change in the component’s state or props.

  • componentWillRecieveProps() – It is invoked when a component receives new props. This is a props exclusive function and is independent of states.
  • shouldComponentUpdate() – It is invoked when a component decides on any changes/updation to the DOM. It allows you to control the component’s behaviour of updating itself. If this method returns true, the component will update. Otherwise, the component will skip the updating. This function can’t be used in the case of forceUpdate().
  • componentWillUpdate() – It is invoked just before the component updating occurs. Here, you can’t change the component state by invoking this.setState() method.
  • render() – It is invoked to examine this.props and this.state and return one of the following types: React elements, Arrays and fragments, Booleans or null, String and Number. If shouldComponentUpdate() returns false, the code inside render() will be invoked again to ensure that the component displays itself properly.
  • componentDidUpdate() – It is invoked immediately after the component updating occurs. In this method, you can put any code inside this that you want to execute once the updating occurs. This method is not invoked for the initial render.

Unmounting 

This method is invoked immediately before a component is destroyed permanently. It performs any necessary cleanup related task such as invalidating timers, and event listeners, canceling network requests or cleaning up DOM elements. If a component instance is unmounted, you cannot mount it again.

Conclusion:

Hope you got the complete understanding of the component lifecycle in ReactJS. If you have any doubts, you can ask me through the common section. Check out more tutorials on ReactJS.

Previous Article

Best eCommerce Mobile App Builders

Next Article

How Feature-Rich MageComp Mobile App Builder Compared To Other Providers?

Write a Comment

Leave a Comment

Your email address will not be published. Required fields are marked *

Get Connect With Us

Subscribe to our email newsletter to get the latest posts delivered right to your email.
Pure inspiration, zero spam ✨