Need to understand about the difference between these two func in ReactJs. ComponentWillMount(){} VS ComponentDidMount(){}
Asked
Active
Viewed 1,217 times
4
-
The former is invoked **right before** the component will mount to the DOM. The latter **right after**. This is suggested by their names... *will* and *did*. – Chris Oct 15 '18 at 14:11
-
Got it. Thank you very much. – ToinX Oct 15 '18 at 14:20
-
1Possible duplicate of [What is the difference between componentWillMount and componentDidMount in ReactJS?](https://stackoverflow.com/questions/29899116/what-is-the-difference-between-componentwillmount-and-componentdidmount-in-react) – Lazar Nikolic Oct 15 '18 at 14:41
3 Answers
4
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

Hemadri Dasari
- 32,666
- 37
- 119
- 162
-
-
constructor is basically to initialise state and do function bindings. componentWillMount does almost same but we don’t use this method much. Because we do all initialisations in constructor and this is recommended over componentWillMount – Hemadri Dasari Oct 15 '18 at 14:24
-
1
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' />

Revansiddh
- 2,932
- 3
- 19
- 33
-
You are saying that ComponentWillMount execute just before rendering component and ComponentDidMount execute just after rendering component. right? – ToinX Oct 15 '18 at 14:33
-
-
1
Difference
componentDidMount()
- invoked immediately after a component is mounted.
- it's gets called only once per mounting so good place for network requests and subscriptions.
- do not assign state here or call setState.
componentWillMount()
- invoked just before mounting occurs.
- the only method which is called on server-rendering
- should avoid using this ( it is a legacy method and will be removed in upcoming react version ).
You should avoid using componentWillMount and use componentDidMount and constructor instead Please check the official react docs for more info

Community
- 1
- 1

Lalit Yadav
- 889
- 9
- 16