How to go async with useEffect
Execute asynchronous tasks with useEffect clean and safely
From calling an API to set a timeout delay, I am sure you already questioned how to do it properly when using the React hook useEffect
. If that sounds still blurred, then this article is for you. If not, you may at least learn a different approach to get the job done or feel more confident while doing it.
I will present 3 ways of doing it safely and tidy. But first, I want to show what you should NOT do.
What you should NOT do ❌
Don’t do the async task directly in the useEffect, instead, ALWAYS wrap your async task into a function and only call it from the useEffect.
Here is an example of what you should NOT do:
useEffect(async () => {
await getData();
},[]);
The code above would block the effect, which is no good. The function passed into useEffect
must remain strictly synchronous.
Also, doing what this BAD example showed, would lead to a React error:
Effect callbacks are synchronous to prevent race conditions.
Alright, now we are safe to move on to the good practices ⬇️