FOSSologyUI icon indicating copy to clipboard operation
FOSSologyUI copied to clipboard

useEffect directly using async function causes issues

Open ChayanDass opened this issue 10 months ago • 3 comments

Description

The useEffect hook directly uses an async function, which can cause unintended behavior. React expects useEffect to return either undefined or a cleanup function, but an async function always returns a promise. This can lead to warnings or execution issues.

How to Reproduce

  1. Look at the following code snippet:
    useEffect(async () => {
        const data = await fetchData();
        setState(data);
    }, []);
    
  2. This may result in console warnings or runtime errors due to improper handling of asynchronous logic inside useEffect.

Expected Behavior

The useEffect should not directly use an async function. Instead, the correct pattern should be followed:

useEffect(() => {
    const  fetchDataAsync= async()  => {
        try {
            const data = await fetchData();
            setState(data);
        } catch (error) {
            console.error("Error fetching data:", error);
        }
    };

    fetchDataAsync();
}, []);

Screenshots

If applicable, add screenshots to help explain your problem.

Versions

  • Last commit id on master:
  • Operating System (lsb_release -a):
  • Browser [e.g., Chrome, Safari]:

Logs

Attach any relevant logs or error messages that could help diagnose the issue.

ChayanDass avatar Feb 22 '25 11:02 ChayanDass

it's needed , to avoid warning and better error handling

ChayanDass avatar Feb 24 '25 06:02 ChayanDass

can I work on this ?

Rahban1 avatar Feb 28 '25 17:02 Rahban1

@Chayan8837 Instead of passing an async function directly to useEffect, we should define the async function inside useEffect and call it properly.

import { useState, useEffect } from "react";

const MyComponent = () => { const [state, setState] = useState(null);

useEffect(() => { const fetchDataAsync = async () => { try { const data = await fetchData(); // Assume fetchData() is an API call setState(data); } catch (error) { console.error("Error fetching data:", error); } };

fetchDataAsync();

}, []); // Empty dependency array ensures this runs only once on mount

return

{state ? JSON.stringify(state) : "Loading..."}
; };

export default MyComponent;

Supriya-57 avatar Mar 05 '25 11:03 Supriya-57

@ChayanDass what is the path of the given code ?? I cannot find it anywhere

Image

Priyank0703 avatar Aug 01 '25 17:08 Priyank0703