Skip to main content

Command Palette

Search for a command to run...

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

Published
•1 min read•View as Markdown
Why can't  we have asynchronous callback function 
                                                     in useEffect()
S

I am a Computer science graduate and passionate frontend web developer and I design and code beautifully simple things, and I love what I do.I like to code things from scratch, and enjoy bringing ideas to life in the browser.Currently on journey of learning Full Stack Javascript Development

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