Reputation: 109
In React 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?
Upvotes: 0
Views: 489
Reputation: 1074595
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.render
method 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.)
Upvotes: 2
Reputation: 1375
componentDidMount - When you want to execute the functionality only once when component is created.It will be executed only once by react.
Upvotes: 0