mangocaptain mangocaptain - 2 months ago 6x
React JSX Question

How does react redux's #applyMiddleware ensure the middleware is only applied once by return the #createStore instead of a store?

How does the changed signature prevent you from apply middleware more than once? It returns a new #createStore, but this method can be used as a parameter again in another #applyMiddleware just as store can be used again, resulting in duplicate middleware.

To ensure that you may only apply middleware once, it operates on
createStore() rather than on store itself. Instead of (store,
middlewares) => store, its signature is (...middlewares) =>
(createStore) => createStore.


Neat question! I didn't quite see how this was obvious either, but I think it works roughly like this:

  1. applyMiddleware() accepts a createStore() function as you pointed out. createStore() is invoked every time applyMiddleware() is called. So, a new store each time these are run.
  2. createStore() accepts specifically enhancers, which are things that add onto a store instance. Things like what applyMiddleware() would provide.
  3. If createStore() is given enhancers, it (indirectly) recursively calls createStore() without any enhancers beyond that. So enhancers are only applied one time using this.

The only way I see to apply middleware more than once would be to implement your own version of createStore(). But you might end up with a circular reference at that point.