What is componentdidmount in Reactjs With Example

Share Me
  •  
  •  
  •  
  • 1
  •  
  •  
  •  
  •  
  •  
  •  
  •  
    1
    Share

Today now in this blog i would like to talk about componentdidmount in react js application. We know that componentdidmount is a method of a component life cycle. So this method call after the component of mounted. Now if you need to call api or need to load data this is best place.

So this a method is a good place to set up any subscriptions. Now If we want to do that, don’t forget to unsubscribe in componentWillUnmount().

Now we can call setState() in componentdidmount() method. Now here i will explain you a chain of component method in a detail. At first need to call constructor() then need to componentWillUnmount() call but here we can not use this method because of react js not the prefer this.So then we can call render() method then we can call componentdidmount() after that again we can call render() method. because of we use setState() Method

componentdidmount() Example

/src/App.js file

import React from 'react'

class App extends React.Component{

    constructor(){
        console.warn('constructor call')
        super();
        this.state = {
            title:null
        }
    }

    componentDidMount(){
        console.warn('componentDidMount call')
        this.setState({
            title:"app component"
        });
    }

    render(){
        console.warn('render call')
        return(
            <div>
                <h1>App Component</h1>
            </div>
        )  
    }
}

export default App;

Read Also : Laravel 8 Eloquent Global Scope Tutorial Example

I hope it will help you. Also you can follow us on Facebook

About code chef

My name is Shahriar sagor. I'm a developer. I live in Bangladesh and I love to write tutorials and tips that will help to other Developer's. I am a big fan of PHP, Javascript, JQuery, Laravel, Codeigniter, VueJS, AngularJS and Bootstrap from the early stage.

View all posts by code chef →