Why You Cannot Pass an Async Function Directly to React's useEffect Hook
React's useEffect hook is commonly used for data fetching, which requires asynchronous functions. However, passing an async function directly as useEffect's first argument is incorrect, because the hook expects that argument to return either nothing or a cleanup function. Since async functions always return a Promise, this conflicts with what useEffect is designed to handle. The correct approach is to define and immediately invoke an async function inside the useEffect callback instead. This pattern keeps the outer function synchronous while still allowing asynchronous operations within the effect.
This is an AI-generated summary. ShortSingh links to the original source for the complete article.
Discussion (0)
Log in to join the discussion and vote.
Log in