When using React’s useEffect
hook we may want to write an asynchronous function, perhaps to fetch some data. There are some important considerations when combining async with useEffect
, discussed further below.
Don’t Do This
The wrong way to write an async function with useEffect
looks something like this:
// DON'T DO THIS
useEffect(async () => {
const data = await fetch('https://someapi.com');
}, [])
The main problem with the code above is that the first argument of useEffect
should be a function that returns a function or nothing at all. Using an async function we return a Promise, which can’t be called as a function. This can lead to unexpected results, including errors where we attempt to access an unmounted component.
Do This Instead
We can instead write our asynchronous code inside the useEffect
hook like this:
useEffect(() => {
const fetchData = async () => {
const data = await fetch('https://someapi.com');
}
fetchData();
}, [])
This is the most stripped down version of how to pair asynchronous code with the useEffect
hook. In practice it’s a good idea to implement error handling and cleanup functions where applicable.