I have used async for anonymous function inside useEffect hook. I have done this so that I can await for the response that I am fetching. Although this is working fine, I've read somewhere on the web that it is a bad practice to write async await inside useEffect hook like this without any proper explaination for it. So just wanted to ask you guys if this is a good practice or bad practice. If it is a bad practice, then what is the disadvantage of writing async await like this in useEffect, and also wanted to know an alternative for this. Big THANKS for your time and help.
import { useEffect, useState } from "react";
export default function FetchPractice() {
const [apiData, setApiData] = useState([]);
useEffect(async () => {
const response = await fetch("https://jsonplaceholder.typicode.com/posts");
const data = await response.json();
setApiData(data);
});
return (
<>
{apiData.map((post) => (
<div
key={post.id}
style={{
border: "1px solid black",
margin: "16px",
padding: "16px",
backgroundColor: "#2d2d2d",
color: "white",
fontWeight: "bold",
}}
>
{JSON.stringify(post)}
</div>
))}
</>
);
}