FrontendDeveloper.in

React question detail

What happens if you return a Promise from useEffect??

You should NOT return a Promise from useEffect. React expects the function passed to useEffect to return either nothing (undefined) or a cleanup function (synchronous function). i.e, It does not expect or handle a returned Promise. If you still return a Promise, React will ignore it silently, and it may lead to bugs or warnings in strict mode.

Incorrect:

useEffect(async () => {
await fetchData(); // ❌ useEffect shouldn't be async
}, []);

Correct:

useEffect(() => {
const fetchData = async () => {
const res = await fetch('/api');
const data = await res.json();
setData(data);
};

fetchData();
}, []);
Back to all React questions
Get LinkedIn Premium at Rs 399