Where should you make AJAX requests in React?

August 03, 2018

In Short

If you need to make an AJAX request in React, add it to the componentDidMount method.

The Explanation

At first glance, the only two logical places to put a React AJAX request are componentDidMount and componentWillMount. But componentWillMount turns out to be a bad idea because the request may complete before the component mounts, and you’ll be stuck trying to set the state on a component that hasn’t mounted yet.

It’s like trying to eat a grape that doesn’t exist yet.

Also, React is now running on an internal engine called Fiber. Fiber allows React to pause and resume work to render animations, make layout changes, and handle gestures as efficiently as possible.

Which is really cool – Fiber is incredibly performant – but now React only calls componentWillMount whenever it thinks it needs to. Which is a recipe for disaster. Because of these reasons, it’s an all-around safer idea to just use componentDidMount.

Get the articles and announcements that I never post publicly: