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?
Lifecycle of Components The three phases are: Mounting, Updating, and Unmounting.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With