How to use async function in useEffect?

Jasmin Virdi - Jun 20 '22 - - Dev Community

In React we all must have used useEffect hook which runs after performing DOM updates and helps us to perform some operation after render.

Before exploring different ways to make async calls inside useEffect let's discuss the problem behind it.

Why we should not use async keyword with useEffect?

Let's take an example to understand this.

const [state, setState] = useState(0)

useEffect(async () => {
    await setState((state) => state + 1);
}, []);
Enter fullscreen mode Exit fullscreen mode

The above piece of code will give error because the async function returns promise and the useEffect doesn't expect callback function to return promise. It should return nothing or a function.

How we can call an asynchronous function inside useEffect? 🤔

In order to make the async call inside useEffect hook we can use the following approaches.

  • Defining async function inside useEffect.
 useEffect(() => {
   const fetchData = async()=> {
     const data = await getData()

     return data
   }
   fetchData()
 }, []);
Enter fullscreen mode Exit fullscreen mode
  • Defining async function outside useEffect.
  const [state, setState] = useState(0)

  const fetchData = useCallback(async()=> {
    const data = await getData();
    setState(data)
  }, [])

  useEffect(() => {
    fetchData()
  }, [fetchData]);
Enter fullscreen mode Exit fullscreen mode

In this case we need to wrap our async function in useCallback to map it with dependency array.

Note - If we do not wrap the function using useCallback hook it will re-render on every update which will result in triggering the useEffect hook again.

I have used these two approaches to use async function with useEffect. Feel free to add any important point or another approach with respect to this topic. 🙌🏻

Happy Learning! 👩🏻‍💻

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Terabox Video Player