154

I realize this is a basic question but I had no luck finding the answer elsewhere.

Is store.dispatch synchronous or asynchronous in Redux ?

In case it is asynchronous is there a possibility to add a callback after the action has been propagated as it is possible with React ?

ps-aux
  • 11,627
  • 25
  • 81
  • 128
  • Notice that the state is updated synchronous (`getState()`) but `mapStateToProps` doesn't. So `this.props.value` is the old value while `getState().value` is the new one - https://codesandbox.io/s/reactredux-forked-0m5eo?file=/Page.js – Mosh Feu Sep 02 '20 at 11:16
  • in the new v7 implementation, dispatch remains synchronous, but if you are using it with react, then the component updates are batched, similar to react setState – gaurav5430 Jun 28 '21 at 19:38

2 Answers2

120

AFAIK, dispatching action is synchronous. In case if you are willing to address the asynchronous call, you can use the thunk-middleware in redux, where dispatch is provided as a callback function which you can invoke as per your convenience. For more info, checkout this answer on SO by Author itself: How to dispatch a Redux action with a timeout?

Community
  • 1
  • 1
Aman Gupta
  • 5,548
  • 10
  • 52
  • 88
  • But many people suggest me: Don't call dispatch in async flow which make redux state becomes unpredictable, you should *sync* to call dispatch. But thunk-middleware just call dispatch after await, that's async flow. Which opinion is correct? sorry for my bad English :) – nuclear Sep 30 '20 at 10:00
  • I am not sure about the challenges you are facing, but the overall idea of using `thunk` action is to facilitate the async flow of the code. e.g. user can dispatch the action once promise is fulfilled. – Aman Gupta Oct 01 '20 at 05:40
92

Nobody knows better than the code itself. =) As you can see dispatch is absolutely synchronous. The only warning here is that store enhancers can (and do) substitute dispatch method. For example, take a look at applyMiddleware enhancer, it lets you jack middlewares in by replacing default dispatch method with its own implementation. Though I never saw any Redux enhancer which would actually remove synchronous nature of dispatch.

pseudosudo
  • 6,270
  • 9
  • 40
  • 53
fkulikov
  • 3,169
  • 13
  • 24
  • 1
    You should update the apply middleware link to [https://github.com/reduxjs/redux/blob/master/src/applyMiddleware.ts#L19](https://github.com/reduxjs/redux/blob/master/src/applyMiddleware.ts#L19) (due to the redux migration from js -> ts, I can't make the edit since it's < 6 characters). Or, perhaps you should reference a commit when they still used js like in your `code itself` link, which would deadlinks due to the 'permalink' aspect of commits. – shanshine Jul 24 '20 at 16:27