javascriptreactjsreact-hooksuse-effectiife

Should I use IIFE in useEffect hook?


Is it good practice to use IIFE in useEffect or I should declare async function and then call it?

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

      setPosts(json);
    })();
  });

Solution

  • As many of you may already know, you cannot pass an async function to the useEffect hook in React. Because of IIFE’s in a roundabout way we still can

    You will see for our useEffect hook that we are able to use async-await syntax by using an IIFE. That’s really it. It’s that simple. IIFEs unlock the potential to use async-await syntax inside the useeffect hook.

    Conclusion IIFE’s are a really powerful JavaScript coding practice that comes in handy for a lot of different use-cases. It turns out that useEffect is no exception.