In the examples given in the redux docs, there always seems to be something being returned from middlewares. However, when I call next(action)
and return nothing everything seems to work fine.
In the redux source it appears to be calling dispatch
on the returned value of every middleware.
This leads me to believe that it provides an optional way to run dispatch after all the middlewares have run.
Can someone confirm if we must ALWAYS return a value from a middleware, and if so why?
So 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.
Redux Middleware allows you to intercept every action sent to the reducer so you can make changes to the action or cancel the action. Middleware helps you with logging, error reporting, making asynchronous requests, and a whole lot more.
Redux middleware provides a third-party extension point between dispatching an action, and the moment it reaches the reducer. People use Redux middleware for logging, crash reporting, talking to an asynchronous API, routing, and more.
Redux thunk is the most popular middleware that allows you to call action creators, which then returns a function instead of an action object.
I actually tweeted about this just the other day.
The store.dispatch()
method by default returns the action that was passed in. Since the middleware pipeline wraps around dispatch()
, each middleware can alter the value being passed through the pipeline on the way in, and alter the return value being passed back.
Many middlewares rely on either being able to return a value themselves, or using the return value coming back. For example, redux-thunk
returns whatever you return from your thunk function, and this is commonly used to be able to return a promise from a thunk so that you can chain dispatch(somePromiseThunk()).then( () => {})
.
If a middleware calls next(action)
but doesn't actually return the value from next()
, it will potentially break those capabilities. The specific behavior will depend on what middleware you have set up, and how you have them ordered.
Because of this, the "correct" practice is that every Redux middleware should return next(action)
by default unless it explicitly wants to change the return value behavior. That ensures the best compatibility and ability to compose middlewares together.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With