Clue Mediator

How to use async functions in useEffect

๐Ÿ“…February 22, 2022
๐Ÿ—ReactJS

The `useEffect` is the place where we mostly write code to get data. Data fetching is an asynchronous function so we can not use async/await in straightforward ways. In this article, we will show you how to use async/await functions in useEffect.

Checkout more articles on ReactJS

The Wrong Way

Donโ€™t do the following approach to call the async function in the useEffect.

useEffect(async () => {
  let response = await fetch('api/data')
  response = await response.json()
  console.log(response);
}, [])

The Correct Way

The correct way is that you have to define the async function within `useEffect` and call it.

useEffect(() => {
  (async function () {
    try {
      let response = await fetch('api/data')
      response = await response.json()
      console.log(response);
    } catch (e) {
      console.error(e);
    }
  })();
}, []);

This is another way to write the code above as follows.

useEffect(() => {
  async function fetchData() {
    try {
      let response = await fetch('api/data')
      response = await response.json()
      console.log(response);
    } catch (e) {
      console.error(e);
    }
  }

  fetchData();
}, []);

async function with useCallback

Use the below code if you want to use async functions outside with eslint.

const fetchData = useCallback(async () => {
  try {
    let response = await fetch('api/data' + userId)
    response = await response.json()
    console.log(response);
  } catch (e) {
    console.error(e);
  }
}, [userId]) // if userId changes, useEffect will run again

useEffect(() => {
  fetchData()
}, [fetchData])

I hope you find this article helpful.
Thank you for reading. Happy Coding..!! ๐Ÿ™‚