DEV Community

Cover image for How to use async functions in useEffect in React.
Franklyn Nmesoma
Franklyn Nmesoma

Posted on

How to use async functions in useEffect in React.

useEffect is usually the place where data fetching happens in React. Data fetching means using asynchronous functions, and using them in useEffect might not be as straightforward as you'd think. Read on to learn more about it!

The wrong way

There's one wrong way to do data fetching in useEffect. If you write the following code, your linter will scream at you!
-------------------------------------------
| I mean you are using a linter right?? |
-------------------------------------------

// ❌ don't do this
useEffect(async () => {
const data = await fetchData();
}, [fetchData])

The issue here is that the first argument of useEffect is supposed to be a function that returns either nothing (undefined) or a function (to clean up side effects). But an async function returns a Promise, which can't be called as a function! It's simply not what the useEffect hook expects for its first argument.

So how do you use asynchronous code inside a useEffect?

Usually the solution is to simply write the data fetching code inside the useEffect itself, like so:

useEffect(() => {
// declare the data fetching function
const fetchData = async () => {
const data = await fetch('https://yourapi.com');
}
// call the function
fetchData()
// make sure to catch any error
.catch(console.error);
}, [])

Summary: You can't make useEffect directly asynchronous because it expects a synchronous cleanup return. Instead, declare and call your async function inside the effect block.

I'm Nmesoma Ononogbo, a software engineer building innovative solutions that empower businesses and create exceptional user experiences, while continuously pushing the boundaries of what's possible with modern technologies.

Top comments (0)