1

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>
      ))}
    </>
  );
}
  • In this way, your API response data is only available to this component only. To avoid that you can use Redux to make it globally accessible. – Amila Senadheera Feb 18 '22 at 13:55

1 Answers1

5

You should not make your useEffect function async, but you can create an async function inside useEffect

useEffect(() => {
    const getDatas = async () => {
        const response = await fetch("https://jsonplaceholder.typicode.com/posts");
        const data = await response.json();
        setApiData(data);
    }
    getDatas()
});

or even

useEffect(() => {
    (async () => {
        const response = await fetch("https://jsonplaceholder.typicode.com/posts");
        const data = await response.json();
        setApiData(data);
    )()
});
dbuchet
  • 1,561
  • 1
  • 5
  • 7
  • Thanks !! I get your point but my code is also working fine, then what is the issue with that, I want to know the problem associated with it. –  Feb 18 '22 at 15:37
  • A moderator has added the link to the "why" :) – dbuchet Feb 18 '22 at 15:59
  • What's the advantage of this over having the async function outside of useEffect with useCallback? – shoopi Jun 04 '22 at 12:38