Why is it recommended to do Ajax in componentDidMount instead of componentWillMount?
According to official React docs, the recommended place to do Ajax requests is in componentDidMount which is a lifecycle method that runs after the React component has been mounted to the DOM.
It sounds a bit counter intuitive to fully render the component before you even start to fetch data. There is a lifecycle method called componentWillMount and at first glance it looks like a perfect method to do Ajax in and set state with the result from the Ajax call. Then the component will be rendered only once. Right?
There is one very simple reason why it is not possible to make your Ajax calls in componentWillMount . From the official react docs:
_...setting state in this method will not trigger a re-rendering_
This means if you make the Ajax call, and set the response to the component state, the component will not re-render. You will not visually see the result in the DOM from your Ajax call, and that is not what you wanted.
But wouldn’t it make sense to do the Ajax call before the component renders to avoid flicker?
You never know how long an Ajax request might take. There are many reasons why your Ajax calls might take longer than you think. Your users might be on mobile with slow internet, your sever might be temporarily slow, etc. That means there will most likely always be a flicker before the Ajax call is loaded. So even if you could make your Ajax call in componentWillMount to load the Ajax before the component mounts, your users would still experience flicker.
Your components that loads Ajax needs to be able to handle empty data. You might for example show a spinner or some encouraging text when the Ajax loads.