useEffect directly using async function causes issues
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
- Look at the following code snippet:
useEffect(async () => { const data = await fetchData(); setState(data); }, []); - 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.
it's needed , to avoid warning and better error handling
can I work on this ?
@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
export default MyComponent;
@ChayanDass what is the path of the given code ?? I cannot find it anywhere