Andrew Kim Andrew Kim - 3 months ago 30
Javascript Question

ReactJS: Why is the convention to fetch data on componentDidMount?

As per this link https://facebook.github.io/react/tips/initial-ajax.html,

I've built a todo app that works great. I fetch my data in

componentDidMount
hook like they say to. I just had a question on the why.

Why do we fetch data after the components mounted? Seems to me it just ends up re-rendering once the data gets set in
setState()
in the hook.

Why not just fetch the data in
constructor()
and set the initial state with data? Wouldn't that be just the 1 render? Seems less expensive even if its only partially re-rendering because of the virtual DOM.

Answer

The fetch will generally be executing asynchronously so it's always going to cause a second render despite it being within componentWillMount or componentDidMount.

I believe they are recommending to put it within the componentDidMount as you may be using a browser dependant implementation of sorts. When executing/rendering components on the server (i.e. within node) only componentWillMount gets executed, and therefore could fall over if you are using a browser/DOM dependant feature. The other lifecyle methods (i.e. componentDidMount) don't get executed on the server, so hence the safety and recommendation I think. Although in general I have found it more useful when needing to do DOM access. Use a universal ajax library (i.e. runs on node/browser) and this probably won't be a concern for you.