why we prefer to write header or api request or ajax code in componentDidMount not in componentWillMount.
need simple and clear difference with example
why we prefer to write header or api request or ajax code in componentDidMount not in componentWillMount.
need simple and clear difference with example
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.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 thencomponentDidMount()
runs, fetching the data, you set yourstate
and that creates a re-render of the component. That's why we usecomponentDidMount()
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).