Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the difference between dispatch and next in Redux middleware?

Tags:

redux

What's the difference between dispatch and next in Redux middleware?

export default function sampleMiddleware(store) {   return next => action => {    store.dispatch(action)    next(action)   } }
like image 691
Héliton Nordt Avatar asked Mar 22 '16 16:03

Héliton Nordt


People also ask

What is Dispatch in Redux?

dispatch is a function of the Redux store. You call store. dispatch to dispatch an action. This is the only way to trigger a state change. With React Redux, your components never access the store directly - connect does it for you.

What is next action in Redux?

The store and action parameters are the current redux store and the action dispatched, respectively. The real magic is the next() function. The next() function is what you call to say "this middleware is done executing, pass this action to the next middleware". In other words, middleware can be asynchronous.

Is Redux dispatch synchronous or asynchronous?

Introduction. By default, Redux's actions are dispatched synchronously, which is a problem for any non-trivial app that needs to communicate with an external API or perform side effects.

Which middleware is best in Redux?

Redux thunk is the most popular middleware that allows you to call action creators, which then returns a function instead of an action object.


2 Answers

Dispatch initiates new action and it's go through full chain of middlewares.

Next – send current action into next middleware in chain.

like image 178
Aleksandr Petrov Avatar answered Sep 19 '22 09:09

Aleksandr Petrov


createStore(reducer,  applyMiddleware(  middlewareA,  middlewareB,  middlewareC  ) ); 

Calling next(action) within middlewareB will cause the action to be passed to middlewareC and then the reducer. Calling dispatch(action) within middlewareB will cause the action to be passed to middlewareA, then middlewareB, then middlewareC, and finally to the reducer, returning the execution back to middlewareB. Calling dispatch() multiple times is a common and valid practice. next() can also be called more than once, but this is not recommended as any action passed to next() will skip the middleware before the current one (for example, potentially skipping the logging middleware).

like image 41
zloctb Avatar answered Sep 20 '22 09:09

zloctb