Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do the React docs recommend doing AJAX in componentDidMount, not componentWillMount?

Tags:

reactjs

I understand why componentDidMount is appropriate for anything that requires DOM access, but an AJAX request doesn’t necessarily or usually need this.

What gives?

like image 305
Alan H. Avatar asked Nov 26 '14 00:11

Alan H.


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.

Why API call is recommended in componentDidMount ()?

Calling API in constructor() or componentWillMount() is not a syntax error but increases code complexity and hampers performance. So, to avoid unnecessary re-rendering and code complexity, it's better to call API after render(), i.e componentDidMount().

Why is componentWillMount deprecated?

The reason for this decision is twofold: All three methods are frequently use incorrectly and there are better alternatives. When asynchronous rendering is implemented in React, misuse of these will be problematic, and the interrupting behavior of error handling could result in memory leaks.

What can I use instead of componentWillMount?

As a general rule don't use componentWillMount at all (if you use the es6 class syntax). use the constructor method instead. This life-cycle method is good for a sync state initialization. componentDidMount in the other hand is good for async state manipulation.


2 Answers

componentDidMount is for side effects. Adding event listeners, AJAX, mutating the DOM, etc.

componentWillMount is rarely useful; especially if you care about server side rendering (adding event listeners causes errors and leaks, and lots of other stuff that can go wrong).

There is talk about removing componentWillMount from class components since it serves the same purpose as the constructor. It will remain on createClass components.

like image 161
Brigand Avatar answered Oct 21 '22 07:10

Brigand


I had the same issue at the beginning, too. I decided to give a try making requests in componentWillMount but it end up in various small issues.

I was triggering rendering when ajax call finishes with new data. At some point rendering of component took more time than getting response from server and at this point ajax callback was triggering render on unmounted component. This is kind of edge case but there is probably more, so it's safer to stick to componentDidMount.

like image 25
daniula Avatar answered Oct 21 '22 07:10

daniula