Component lifecycle and async operation initiation

(Pedro Felix) #1

Consider a scenario where a stateful component is responsible for fetching information from an external HTTP API and presenting it. If I understand the new 16.3 lifecycle correctly,

  • componentDidMount is the proper place to start the first asynchronous fetch.
  • componentWillUnmount should be used to cancel any pending asynchronous fetch.

However, it is not clear to me what is the proper place to initiate additional fetches as a consequence of asynchronous events, such as a button onClick or a setInterval callback.
Namely, should the event handler:

  • Change the state via setState (e.g. setting a loading: true) and immediately start the asynchronous fetch (even before the new state is committed).
  • Or, change the state via setState and only start the asynchronous fetch on the componentDidUpdate, i.e. after the new state is commited on the DOM.