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?
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.
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().
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.
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.
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.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With