Algobook
- The developer's handbook
mode-switch
back-button
Buy Me A Coffee
Mon May 15 2023

How to perform an async operation in useEffect hook in React

In this short guide, I will show how we can call an async function in our useEffect hook in React and wait for the response with await. A common scenario for this is when we want to call an API or similar from our React component when it is mounted.

Async call in useEffect

Let's dive right in. I will share the example and explain below the code snippet

import { useEffect } from "react"; const Component = () => { useEffect(() => { const fetchData = async () => { const reponse = await fetch(MY_API); // Logic goes here... }; fetchData(); }, []); return "My component"; };

There we go. Some notes of the above code:

  • In our useEffect we will create a new function called fetchData inside of the hook, that is async. And then we will call the function from the hook.

  • React wants us to create it like this instead of making the hook callback async. The reason is that it can cause race conditions if the hooks are asynchronous.

  • Inside of fetchData we can await our response and do what we like, setting a state or similar for example.

Outro

That's it for this short tutorial on how we can perform asynchronous operations in our useEffect hooks. Thanks for reading!

All the best,

signatureMon May 15 2023
See all our articles