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
- How to validate a checkbox list in React
- How to display a PDF in React
- How to render curly braces as plain text in React
- Implement server side pagination in React AG Grid
- Create guided tours in the React app
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..!! ๐