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:

  1. Inside your component, define the useEffect hook.
  2. Inside the useEffect, create an async function.
  3. In this function, you can use your async/await syntax.
  4. 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.

🔗 https://www.codu.co/articles/learn-immediately-invoked-function-expressions-iifes-in-javascript-ozm9rmg9

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! ❤️

Reactjs
Avatar for Niall Maher

Written by Niall Maher

Founder of Codú - The web developer community! I've worked in nearly every corner of technology businesses; Lead Developer, Software Architect, Product Manager, CTO and now happily a Founder.

Loading

Fetching comments

Hey! 👋

Got something to say?

or to leave a comment.