In React.js should I make my initial network request in componentWillMount or componentDidMount?

You should do requests in componentDidMount.

If componentWillMount is called before rendering the component, isn’t it better to make the request and set the state here?

No because the request won’t finish by the time the component is rendered anyway.

If I do so in componentDidMount, the component is rendered, the request is made, the state is changed, then the component is re-rendered. Why isn’t it better to make the request before anything is rendered?

Because any network request is asynchronous. You can’t avoid a second render anyway unless you cached the data (and in this case you wouldn’t need to fire the request at all). You can’t avoid a second render by firing it earlier. It won’t help.

In future versions of React we expect that componentWillMount will fire more than once in some cases, so you should use componentDidMount for network requests.

Leave a Comment