Sam
Sam

Reputation: 30342

Calling action from constructor vs a life cycle method

Where's the best place to call an action that will make an API call to hydrate my state? Constructor or one of the life cycle methods e.g. ComponentWillMount?

Upvotes: 21

Views: 10632

Answers (1)

Mayank Shukla
Mayank Shukla

Reputation: 104459

It will be better to make the api calls from lifecycle method componentDidMount, react doc also suggested the same.

As per DOC:

componentDidMount:

componentDidMount() is invoked immediately after a component is mounted. Initialization that requires DOM nodes should go here. If you need to load data from a remote endpoint, this is a good place to instantiate the network request. Setting state in this method will trigger a re-rendering.

Upvotes: 16

Related Questions