Reputation: 3451
I want to use the async/await pattern in my useEffect
React hook and I'm getting an ESLint warning that I don't understand.
Here is my code that causes the warning
useEffect(async () => {
const delay = () => new Promise((resolve) => setTimeout(resolve, 1000));
async function getData() {
await delay();
}
getData();
}, []);
and the warning:
ESLint: Effect callbacks are synchronous to prevent race conditions. Put the async function inside: (react-hooks/exhaustive-deps)
The answer from a similar question says to add useCallback
, but as I have no dependencies, it does not seem to help.
How to fix missing dependency warning when using useEffect React Hook
Here is what that incorrect answer looks like:
const delay = () => new Promise((resolve) => setTimeout(resolve, 1000));
async function getData() {
await delay();
}
getData();
},[]), []);
Upvotes: 0
Views: 518
Reputation: 87
You shouldn't make a usEffect
asynchronous. Instead add it to the outside of your useEffect
. Here is a Stackoverflow answer that gives one reason why. Instead:
const delay = () => new Promise((resolve) => setTimeout(resolve, 1000));
async function getData() {
await delay();
}
useEffect(() => { // don't need async here
getData();
}, []);
Upvotes: 1
Reputation: 1586
useEffect(async () => { // don't need async here
const delay = () => new Promise((resolve) => setTimeout(resolve, 1000));
async function getData() {
await delay();
}
getData();
}, []);
The error is telling you not to use async
in the call to useEffect()
itself. Look here, you have this exact anti-pattern: https://dev.to/danialdezfouli/what-s-wrong-with-the-async-function-in-useeffect-4jne
Also notice how the parentheses in that example are being used to scope the async
function as an IIFE so it runs without being explicitly called.
Upvotes: 0