How to use Async/Await in a useEffect
Once you start using async/await it can be hard to return to the alternatives...
It makes your code look like synchronous code, which is easier to read and write.
In React, the useEffect
hook is often used to perform side effects, like fetching data from an API.
Unfortunately, the function we pass to a useEffect
can't be async
.
Instead, you should create a separate async function inside the useEffect
, and then call that function.
Here's how you can do it:
- Inside your component, define the
useEffect
hook. - Inside the useEffect, create an async function.
- In this function, you can use your async/await syntax.
- Finally, call the async function.
As always, I think examples help with understanding:
import { useEffect, useState } from "react"; const ExampleComponent = () => { const [data, setData] = useState(null); useEffect(() => { const fetchData = async () => { try { const response = await fetch("https://my-fake-api.com/data"); const result = await response.json(); setData(result); } catch (error) { console.error(error); } }; // Call the function fetchData(); }, []); return <div>{data ? <div>{data}</div> : <div>Loading...</div>}</div>; }; export default ExampleComponent;
Here, we define an async
function fetchData
. Inside fetchData, we use a try/catch block to fetch the data from the API, and then we set the data in the state. After defining fetchData
, we call it. 🪄
With an IFFE
If you don't know what an "IFFE" is, I have got an article here that will explain it.
I think it's a cleaner way to use async/await in a useEffect
because it doesn't require defining a separate async function.
However, it might be a bit less intuitive to understand at first if you're unfamiliar with IIFEs.
Here's an example using an IFFE:
import { useEffect, useState } from "react"; const ExampleComponent = () => { const [data, setData] = useState(null); useEffect(() => { (async () => { try { const response = await fetch("https://my-fake-api.com/data"); const result = await response.json(); setData(result); } catch (error) { console.error(error); } })(); // Call it right away ✨ }, []); return <div>{data ? <div>{data}</div> : <div>Loading...</div>}</div>; }; export default ExampleComponent;
That's it!
That's how you can use async/await in a useEffect
in React.
Happy coding! ❤️