Should I use IIFE in useEffect hook?
Asked Answered
R

4

8

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);
    })();
  });
Remorseful answered 15/3, 2022 at 10:16 Comment(1)
You can leave IIFE it should not have any issues with this.Barayon
S
11

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.

Seidel answered 15/3, 2022 at 10:36 Comment(0)
C
1

I would suggest using IIFE rather than declaring async function and calling it. coz you are going to use the declared async function only once in the useEffect and its precisely the use case for IIFE.

Cultus answered 15/3, 2022 at 10:40 Comment(0)
M
1

I would advocate against it if you somehow interact with your components' state (useState).

https://www.reddit.com/r/reactjs/comments/lhj7nb/batching_usestate_in_async_useeffect/

     const result = await fetch(
        "https://jsonplaceholder.typicode.com/posts"
      ); 
     result.then((json) => setPosts(json))
  }

No it is definitelly not. You will mess around a lot with the way things work for react under the hood. Don't get carried away about what has been said before.

If you want to fetch posts based on some reaction, the right away for it would be to have your useEffect react to the desired state.

like userReachEndPage state would suit a useEffect(() => fetch ,[userReachEndPage]) If you were to react from a button then maybe wrap it in a callback, to avoid the extra rerender.

Never would be the right answer as to using IIF inside useeffect.

Mell answered 23/2, 2023 at 21:54 Comment(0)
D
0

I would avoid this pattern inside effects as much as possible. Here some reasons:

Is it better than the basic syntax?

This will do the trick and I think it's legit to say it's way more readable. See the last point for a deeper explanation.

useEffect(() => {
  void myService(...).catch(...);
  ...
}, [...]);

If you don't want to create a separate file for your service for some reason, you can declare the service as constant right in the same file. I suggest to do it outside the component or use the useCallback(...) hook.

Testability (Unit tests)

It is hard to test a IIFE inside an effect. I would move it into its own file and export it as a constant. Then It would be available to be imported in a future test suite.

Separation of concerns

It looks like a common trend for starter tutorials to implement everything in a single file. But in my experience, it just won't work well in real world. You'll eventually find yourself working in a new version of the component. Even a new version of the application which doesn't have that component, or even it won't relay in React or effects at all (i.e. server components with react, vue, svelte, etc...). Then you'll need to trash the effect and refactor the fetch code into something you can port.

Inversion of control

At some point, you might want to fake / mock the service (IIFE) to test the component or define a different API. To avoid future problems, ideally your component should receive the service as a dependency, or even be wrapped by an adapter which responsibility is to put those two concerns together instead of coupling those two guys forever.

Reusability and Maintainability

Even if you are using something only once, "nothing lasts forever". Actually, your service looks to me like the most reusable part of the application. Additionally, depending on how much your project will grow, you'll appreciate to have all the API related stuff put together in order to find it fast, and avoid having to think hard constantly about where to put new code.

Now imagine a new team mate is joining the project...

A word about choosing the right tools

Effects are imposed by React (kind of), so we have to deal with them. However, AA is just syntax sugar to make promises look more fancy and readable. Honestly, I think it's not legit to use syntax sugar (AA) if it requires to be wrapped with syntax... lemons? (IIFE).

There is an underlying general conclusion in top of this: Whenever you choose a tool (feature), ensure there are legit reasons to do it in the specific context you're dealing with. Something can be powerful or fancy looking, but it might not be the best option though.

Disunite answered 2/4 at 10:55 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.