Use componentWillMount or componentDidMount lifecycle functions for async request in React
I am reading up on react lifecycle and am getting a little confused. Some recommend using componentWillMount to make ajax calls:
Calling setState in componentDidMount will trigger another render() call and it can lead to layout thrashing.
and in other places it says not to put ajax calls in the componentWillMount:
https://medium.com/@baphemot/understanding-reactjs-component-life-cycle-823a640b3e8d
...this function might end up being called multiple times before the initial render is called so might result in triggering multiple side-effects. Due to this fact it is not recommended to use this function for any side-effect causing operations.
Which is correct?
Answers 1
The React docs recommend on using
componentDidMount
for making network RequestsAs per the the case for
componentWillMount
:EDIT:
This lifecycle is deprecated since
v16.3.0
of react and is no longer encouraged for usage.However its renamed toUNSAFE_componentWillUpdate
and is expected to work till at least v17 of reactBefore v16.3.0
An asynchronous call to fetch data will not return before the render happens. This means the component will render with empty data at least once.
There is no way to “pause” rendering to wait for data to arrive. You cannot return a promise from
componentWillMount
or wrangle in asetTimeout
somehow. The right way to handle this is to setup the component’s initial state so that it’s valid for rendering.To Sum it up
In practice,
componentDidMount
is the best place to put calls to fetch data, for two reasons:undefined
state that causes errors.componentWillMount
will actually be called twice – once on the server, and again on the client – which is probably not what you want. Putting the data loading code incomponentDidMount
will ensure that data is only fetched from the client.