Calling setState() behind an async call in ReactJS

I have blogged about how dangerous it is to use setState() during component lifecycle methods or render() functions. This is because the component can end up in an endless nested deep render. Dan Abromovic and the creators of ReactJS have also talked a lot about this subject. This is why we associate setState() with an event, like a button click.

A similar design pattern exists in ReactJS when we try to use setState() after calling an async function. In Redux we would not have this problem of course. However let's say you are rendering a location pin inside Google Map without the complexities of Redux state management. So all we want is:

  1. Geocode an address by calling Google Maps API
  2. Wait for the API response
  3. Set the map marker state so you get the pin at the right location

If step (3), the setState() function, is called before we get the API response, ReactJS is most definitely going to throw an error? Why? Because calling setState() before the component has fully mounted, or is still rendering, or is re-rendering, is a cardinal sin in ReactJS. 

So to make sure that step (3) is always called at the very end, we can easily make use of the async functions. Note that in setState(), the common pattern to call it synchronously, is to bind it to a function. Checkout this working code below to understand what I am saying:

Post a Comment