Search code examples
reduxredux-thunk

Does applying Redux-Thunk midleware to redux change all actions to be executed asynchronously?


I have a project in which I have applied the redux-thunk middleware to my redux store. Now I have several thunks in my code and this are also being dispatched, but they return ThunkAction<Promise<void>, void, void, AnyAction> so I assume these are async.

In other places of my code I’m directly calling the dispatch method on the store. Does this actions also become asynchronous as an effect of applying middleware or do they remain synchronous?

For example If i do:

store.dispatch(someAction);

Would that still be synchronous?

Thanks in advance.


Solution

  • Yes.

    Dispatching is 100% synchronous by default.

    If you add middleware, a middleware may alter, delay, or stop an action from progressing through the dispatch pipeline.

    However, in this case, the redux-thunk middleware does not do anything asynchronous. It simply checks to see if the "action" is actually a function, and if so, executes it immediately:

    function createThunkMiddleware(extraArgument) {
      return ({ dispatch, getState }) => (next) => (action) => {
        if (typeof action === 'function') {
          return action(dispatch, getState, extraArgument);
        }
    
        return next(action);
      };
    }
    

    If the thunk middleware is applied, store.dispatch(someThunkFunction) will return whatever the thunk function returns. So, if you return a promise from the thunk, that promise will be returned from store.dispatch().

    For the TS types, the first generic argument should indicate the expected return type of the thunk function. However, you would likely actually have to specify that yourself - it shouldn't be appearing randomly.