How to use async functions in useEffect
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.
1 2 3 4 5 | 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.
1 2 3 4 5 6 7 8 9 10 11 | 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.
1 2 3 4 5 6 7 8 9 10 11 12 13 | 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.
1 2 3 4 5 6 7 8 9 10 11 12 13 | 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..!! 🙂