Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to define the order of reducers execution in Redux?

Tags:

reactjs

redux

Assume I have action A which is dispatched to reducer R1 and R2. I also have smart component C which is connected to the states returned by R1 and R2

Is it possible that component C were rerendered when R1 is executed but before R2 is executed?

How if I want to rerender C only when both R1 and R2 are executed? Or is it possible to tell Redux dispatcher to dispatch the action to R2 first?

*R1 is actually the results state returned by redux normalizr and R2 is the entities state. The entities are needed to denormalize the results

like image 376
Pahlevi Fikri Auliya Avatar asked Mar 10 '16 23:03

Pahlevi Fikri Auliya


People also ask

How do reducers work in Redux?

Reducers are functions that take the current state and an action as arguments, and return a new state result. In other words, (state, action) => newState .

How do you define initial state in reducer?

There are two main ways to initialize state for your application. The createStore method can accept an optional preloadedState value as its second argument. Reducers can also specify an initial value by looking for an incoming state argument that is undefined , and returning the value they'd like to use as a default.

How do I dispatch action in reducer?

Dispatching an action within a reducer is an anti-pattern. Your reducer should be without side effects, simply digesting the action payload and returning a new state object. Adding listeners and dispatching actions within the reducer can lead to chained actions and other side effects.

Does Redux call all reducers?

One frequently asked question is whether Redux "calls all reducers" when dispatching an action. Since there really is only one root reducer function, the default answer is "no, it does not".


1 Answers

Is it possible that component C were rerendered when R1 is executed but before R2 is executed?

No, it is not possible if you use a single store like Redux docs suggest.

In Redux, you combine reducers with combineReducers(). This means that from Redux’s point of view, there is only a single reducer, and it is synchronous. Sure, it calls your two reducers, but the Redux store only begins notifying subscribers after it gets the new state value from its root reducer, so it is guaranteed that all your reducers have already been executed by the time the views are notified.

like image 113
Dan Abramov Avatar answered Oct 06 '22 05:10

Dan Abramov