1

why we prefer to write header or api request or ajax code in componentDidMount not in componentWillMount.

need simple and clear difference with example

dxtmhjn
  • 33
  • 4
  • Possible duplicate of [Why do the React docs recommend doing AJAX in componentDidMount, not componentWillMount?](https://stackoverflow.com/questions/27139366/why-do-the-react-docs-recommend-doing-ajax-in-componentdidmount-not-componentwi) – lux Aug 24 '17 at 18:54

2 Answers2

1

You should use componentDidMount() because you need the component to be rendered in order to populate it with the data that you're fetching from the API.

componentWillMount(){
   //Fetch API and set the State
}

render(){
   return(<div>{this.state.myData}</div>)
}

When componentWillMount() fires up the <div> hasn't been rendered yet (does not exist at the moment in the DOM).

When using componentDidMount() in the other hand. The render method runs first creating the <div> element in the DOM, after that then componentDidMount() runs, fetching the data, you set your state and that creates a re-render of the component. That's why we use componentDidMount() to fetch data from the API. you can find more information here.

caveat: You should validate the state so you don't get undefined the first time the component is render (without the data from the API).

Edgar Henriquez
  • 1,373
  • 1
  • 14
  • 17
  • edgaromar90 the same case with constructor also. we usually set temporary state in constructor and constructor invokes before the initial render. both constuctor and willMount invokes before initial render, then why we are not using in componentWillMount – dxtmhjn Aug 24 '17 at 19:37
  • "componentWillMount() is invoked immediately before mounting occurs. It is called before render(), therefore setting state synchronously in this method will not trigger a re-rendering. Avoid introducing any side-effects or subscriptions in this method." - from [React doc](https://facebook.github.io/react/docs/react-component.html#componentdidmount) – Edgar Henriquez Aug 24 '17 at 19:55
0

edgaromar90 the same case with constructor also. we usually set temporary state in constructor and constructor invokes before the initial render. both constuctor and willMount invokes before initial render, then why we are not using in componentWillMount

dxtmhjn
  • 33
  • 4