最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Should I use IIFE in useEffect hook? - Stack Overflow

programmeradmin6浏览0评论

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(
        ";
      );
      const json = await response.json();

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

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./posts"
      );
      const json = await response.json();

      setPosts(json);
    })();
  });
Share Improve this question asked Mar 15, 2022 at 10:16 AlmaG3stAlmaG3st 3816 silver badges15 bronze badges 1
  • 1 You can leave IIFE it should not have any issues with this. – Damian Busz Commented Mar 15, 2022 at 10:25
Add a ment  | 

4 Answers 4

Reset to default 13

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 es in handy for a lot of different use-cases. It turns out that useEffect is no exception.

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.

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

https://www.reddit./r/reactjs/ments/lhj7nb/batching_usestate_in_async_useeffect/

     const result = await fetch(
        "https://jsonplaceholder.typicode./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.

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 ponent 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 mon 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 ponent. Even a new version of the application which doesn't have that ponent, or even it won't relay in React or effects at all (i.e. server ponents 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 ponent or define a different API. To avoid future problems, ideally your ponent 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.

发布评论

评论列表(0)

  1. 暂无评论