Async functions with React's useEffect hook

It may not be pretty, but the easiest way to call an async function in useEffect is to use an Immediately Invoked Function Expression (IIFE).

useEffect(() => {
  (async () => {
    try {
      await doSomething();
    } catch (err) {
      console.error(err);
    }
  })();
}, []);

That's it! Don't overthink it.

Find me on Twitter for other straightforward solutions.

A newsletter for curious developers

Join me on the fantastic journey of software development. JavaScript, CSS, HTML, React, Next.js, Flutter, GraphQL, Fauna.