Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

In the react docs it recommends making initial network requests in the componentDidMount method:

componentDidMount() is invoked immediately after a component is mounted. Initialization that requires DOM nodes should go here. If you need to load data from a remote endpoint, this is a good place to instantiate the network request. Setting state in this method will trigger a re-rendering.

If componentWillMount is called before rendering the component, isn't it better to make the request and set the state here? 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?

like image 925
TimothyBuktu Avatar asked Jan 12 '17 11:01

TimothyBuktu


People also ask

When should I use componentDidMount vs componentWillMount?

componentDidMount() is only called once, on the client, compared to componentWillMount() which is called twice, once to the server and once on the client. It is called after the initial render when the client received data from the server and before the data is displayed in the browser.

When should I use componentDidMount?

The componentDidMount() method allows us to execute the React code when the component is already placed in the DOM (Document Object Model). This method is called during the Mounting phase of the React Life-cycle i.e after the component is rendered.

What happens first the render or the componentDidMount?

componentDidMount will only be called once after the first render.


1 Answers

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.

like image 180
Dan Abramov Avatar answered Sep 24 '22 19:09

Dan Abramov