Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between ComponentWillMount and ComponentDidMount in React JS?

Tags:

reactjs

Need to understand about the difference between these two func in ReactJs. ComponentWillMount(){} VS ComponentDidMount(){}

like image 633
ToinX Avatar asked Sep 13 '25 04:09

ToinX


2 Answers

componentWillMount() gets called before first render whereas componentDidMount() gets called after first render. Both of these components gets called only once

Please note that componentWillMount() is deprecated in latest React version v16

like image 148
Hemadri Dasari Avatar answered Sep 16 '25 01:09

Hemadri Dasari


Most discussed topic still explaining my understanding. ComponentWillMount executes before render as name suggest ComponentAfterMount executes before render once component gets rendered on screen as name suggest.

look at console logs in example

class App extends React.Component {
  componentWillMount(){
     console.log("console loging before component will mount");
  }
  componentDidMount(){
     console.log("console loging after mounting component");
  }
  render(){
    console.log("rendering component")
    return(
     <div> component</div>
    )
  }
}
ReactDOM.render(<App />, document.getElementById('root'))
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>

<div id='root' />
like image 37
Revansiddh Avatar answered Sep 16 '25 02:09

Revansiddh