Need to understand about the difference between these two func in ReactJs. ComponentWillMount(){} VS ComponentDidMount(){}
-
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– Chris2018年10月15日 14:11:35 +00:00Commented Oct 15, 2018 at 14:11
-
Got it. Thank you very much.ToinX– ToinX2018年10月15日 14:20:41 +00:00Commented Oct 15, 2018 at 14:20
-
1Possible duplicate of What is the difference between componentWillMount and componentDidMount in ReactJS?Lazar Nikolic– Lazar Nikolic2018年10月15日 14:41:40 +00:00Commented Oct 15, 2018 at 14:41
3 Answers 3
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
3 Comments
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' />
3 Comments
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