How to Use async/await in React useEffect() Hook?

Using async/await inside React useEffect() hook

You cannot directly make the callback function supplied to the useEffect hook async because:

When you attempt to make useEffect's callback async, you will see the following warning:

// Warning: Effect callbacks are synchronous to prevent race conditions
useEffect(async () => {
  const products = await fetch(`${API_URL}/products.json`);
  setProducts(products);
}, []);

Therefore, to use async/await inside the useEffect hook, you can do either of the following:

  1. Create a Self-Invoking Anonymous Function;
  2. Create a Nested Named Function.

Create a Self-Invoking Anonymous Function

You can simply create a self-invoking anonymous function inside the useEffect hook that does the asynchronous call(s) and performs other related tasks. For example:

// ...

useEffect(() => {
    (async function() {
      const products = await fetch(`${API_URL}/products.json`);
      setProducts(products);
    })();
}, []);

// ...

Create a Nested Named Function

You can create a named asynchronous function that you can call right after it is declared, for example, like so:

// ...

useEffect(() => {
    const fetchData = async () => {
      const products = await fetch(`${API_URL}/products.json`);
      setProducts(products);
    });

    fetchData();
}, []);

// ...

Hope you found this post useful. It was published . Please show your love and support by sharing this post.