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:
- Starting ajax
- As the documentation says, doing subscriptions to things (for instance, if the component receives updates in some way that isn’t handled by its parent component, such as a stream of events from a web socket)
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:
- In the component’s constructor, you create its default state saying it’s loading something.
componentDidMount, you start the ajax call that loads the thing.
- When (if) the ajax call succeeds, you use the data from the call to update state
- You write the
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.)