What is componentdidmount in Reactjs With Example

React.js

Nicesnippets

335

22-01-2020


In this blog i would like to explain about componentdidmount in react js. componentdidmount is a method of component life cycle. this method call after component mounted. if you need to call api or load data this is best place.

This method is a good place to set up any subscriptions. If you do that, don’t forget to unsubscribe in componentWillUnmount().

You can call setState() in componentdidmount() method. i am explain you chain of component method in detail. first call constructor() then componentWillUnmount() call but we can not use this method beause of react js not prefer this. then call render() method then call componentdidmount() after that again call render() method. beause 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;

I hope it can help you...


Recommended Posts