componentDidMount is used during the mounting phase, for example, one can
setState and wrap it in
componentDidMount. But, one can use
setState directly and then
render the component.
In which cases should I prefer
componentDidMount for a mounting phase?
It’s useful for several things:
Basically any time you want to kick off a process when the component is first mounted.
The classic example is a component that loads something via ajax. It goes like this:
componentDidMount, you start the ajax call that loads the thing.
rendermethod so that it knows about the loading state and shows either loading or the thing that it loaded (or a loading error) appropriately.
(There are situations where you don’t want to do that, where you want to load the thing in the parent component instead and only create the component that shows it when you have the thing. But other times doing it directly in the component isn’t uncommon, and it makes a useful example.)