Why do we need middleware for async flow in redux

ref – https://stackoverflow.com/questions/34570758/why-do-we-need-middleware-for-async-flow-in-redux

Why do we need middleware for async flow in redux?

…for example, Why can’t the container component call the async API, and then dispatch the actions?

Solution

There is nothing wrong with this approach. It’s just inconvenient in a large application because you’ll have different components performing the same actions, you might want to:

  • debounce some actions
  • or keep some local state like auto-incrementing IDs close to action creators
  • etc.
  • So it is just easier from the maintenance point of view to extract action creators into separate functions.

    Therefore, the benefit of using middleware like Redux Thunk or Redux Promise is that components aren’t aware of how action creators are implemented

    and whether they care about Redux state,
    whether they are synchronous or asynchronous,
    and whether or not they call other action creators.

    The downside is a little bit of indirection, but we believe it’s worth it in real applications.

    Using middleware – By using middle are for async management, component doesn’t care that the action creator is async. It just calls dispatch normally, it can also use mapDispatchToProps to bind such action creator with a short syntax, etc. The components don’t know how action creators are implemented, and you can switch between different async approaches (Redux Thunk, Redux Promise, Redux Saga) without changing the components.

    Custom way (implement it by hand) – On the other hand, explicit approach, your components know exactly that a specific call is async, and needs dispatch to be passed by some convention (for example, as a sync parameter).

    Also think about how this code will change. Say we want to have a second data loading function, and to combine them in a single action creator.

    We need to be mindful of what kind of action creator we are calling:

    With Redux Thunk action creators can dispatch the result of other action creators and not even think whether those are synchronous or asynchronous:

    If you need to change it to be synchronous, you can also do this without changing any calling code: