Skip to content

How to Fix useEffect with Async/Await

DodaTech Updated 2026-06-26 1 min read

The Problem

In this quick-fix, you'll learn how to correctly use async/await inside useEffect. This matters because passing async function directly to useEffect causes warnings. In real-world applications, this pattern appears in data fetching file processing async initialization.

The Wrong Way

function UserList() {
  const [users, setUsers] = useState([]);
  useEffect(async () => {
    const r = await fetch('/api/users');
    const d = await r.json();
    setUsers(d);
  }, []);
  return <ul>{users.map(u=><li key={u.id}>{u.name}</li>)}</ul>;
}
Warning: useEffect callback must not return anything besides a function

The Right Way

function UserList() {
  const [users, setUsers] = useState([]);
  const [error, setError] = useState(null);
  useEffect(() => {
    const c = new AbortController();
    async function fetchUsers() {
      try { const r = await fetch('/api/users', {signal:c.signal}); const d = await r.json(); setUsers(d); }
      catch(e) { if(e.name!=='AbortError') setError(e.message); }
    }
    fetchUsers();
    return () => c.abort();
  }, []);
  if(error) return <div>Error: {error}</div>;
  return <ul>{users.map(u=><li key={u.id}>{u.name}</li>)}</ul>;
}
No warnings -- async defined and called inside callback

Prevention

  • Define async functions inside useEffect not as callback
  • Handle errors with try-catch inside async function
  • Use AbortController to cancel on unmount

FAQ

### Why cant useEffect be async directly??

useEffect expects callback to return nothing or cleanup function. Async function returns Promise which React doesnt recognize as valid return.

How to handle race conditions with multiple async calls??

Use AbortController to cancel previous requests. Use boolean flag let cancelled = false and check before setting state.

Can I use .then() instead of async/await??

Yes .then() works fine. Both require error handling and cleanup. Choose readable style for your team.

This guide is brought to you by DodaTech -- built by the developers of Doda Browser, DodaZIP, and Durga Antivirus Pro.

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro