HomeAbout

useEffect w/ Async Function

Async Function in useEffect

When you have async function like:

async () => { try { const response = await fetch(`https://www.reddit.com/r/${subreddit}.json`); const json = await response.json(); setPosts(json.data.children.map(it => it.data)); } catch (e) { console.error(e); } }

Async function returns a promise.

useEffect expects a cleanup function or nothing.

You can use IIFE:

useEffect(() => { (async function() { try { const response = await fetch( `https://www.reddit.com/r/${subreddit}.json` ); const json = await response.json(); setPosts(json.data.children.map(it => it.data)); } catch (e) { console.error(e); } })(); }, []);

OR define and immediately call it:

useEffect(() => { async function fetchData() { try { const response = await fetch( `https://www.reddit.com/r/${subreddit}.json` ); const json = await response.json(); setPosts(json.data.children.map(it => it.data)); } catch (e) { console.error(e); } }; fetchData(); }, []);

Do NOT extract the async function out.

  • It is NOT clear to the user whether the called async function has a cleanup function attached to it or not.
  • If the cleanup function is needed, it will lead to a memory leak.
AboutContact