Why can't  we have asynchronous callback function 
                                                     in useEffect()

Why can't we have asynchronous callback function in useEffect()

Async calls in javascript can help us in API calls and fetching data from server, but why is it we can't use async calls with useEffect like shown below:

useEffect( async () => {
 // api call or data fetch
}, [])

// It gives an ERROR...

We can not directly make the callback function in useEffect hook async because of two reasons:

  1. async functions implicitly returns a promise.

  2. useEffect expects its callback to either return nothing or a cleanup function.

So, basically React.js useEffect hook expects a cleanup function returned from it which is called when the component unmounts. Using async here will cause a bug as cleanup function will never get called.

To work around this we can:

  • Create a self-invoking anonymous function.
useEffect(() => {
   (async function () {
     console.log('any api call')
   })();
   return() => {
     // perform any cleanup
    }
}, [])
  • Create a nested named function
useEffect(() => {
  async function fetchData() {
    // You can await here
    const response = await MyAPI.getData(someId);
    // ...
  }
  fetchData();
  return() => {
    // perform cleanup
  }
}, [])

Thanks for reading.....

Shubham Singh