Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling action from constructor vs a life cycle method

Tags:

reactjs

redux

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?

like image 514
Sam Avatar asked Jun 28 '17 20:06

Sam


People also ask

What are three main methods of component's lifecycle?

Lifecycle of Components The three phases are: Mounting, Updating, and Unmounting.

Which is called first constructor or componentDidMount?

constructor will be called pre-render and componentDidMount post-render. The componentWillMount method is called right before a component mounts or the render method is called.

Why do we use the life cycle method?

This lifecycle can be useful when, for some reason, you do not want React to render your current state. Every time we call setState() here the component re-renders. Moreover, this component usually is used to know if a particular component is not affected directly by the prop changes or the state.

In which lifecycle method do you do API calls?

componentDidMount() method For example, we are going to fetch any data from an API then API call should be placed in this lifecycle method, and then we get the response, we can call the setState() method and render the element with updated data.


1 Answers

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.

like image 133
Mayank Shukla Avatar answered Oct 05 '22 05:10

Mayank Shukla