You cannot directly make the callback function supplied to the useEffect
hook async
because:
async
functions implicitly return a promise, and;useEffect
expects its callback to either return nothing or a clean-up function.
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:
This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.