Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

All reducers will be invoked when an action is dispatched?

Tags:

redux

I am using combineReducers to combine all the reducers to create the store, does it mean that any action dispatched from any view will trigger all the reducers being invoked to check the action type?Is it kind of low efficiency?

Or I don't fully understand the redux design principle?

like image 298
hjl Avatar asked Nov 08 '15 04:11

hjl


People also ask

What happens when you try to dispatch an action within a 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".

What happens when we dispatch an action in Redux?

Redux uses a "one-way data flow" app structure When something happens in the app: The UI dispatches an action. The store runs the reducers, and the state is updated based on what occurred. The store notifies the UI that the state has changed.

How action and reducer are connected?

When you dispatch an action creator it passes the action object to the root reducer. The action object is passed through the entire state tree and any reducers that process the action type consume it.


1 Answers

Yes, that is correct.

However one option you have to optimize this behaviour (suggested from the Redux docs) is to use 'reselect' https://github.com/rackt/reselect

Reselect basically allows you to create memoized selectors, whereby you can say that props A depends on state B and state C, and therefore only recompute props A if state B or state C changes.

Notice that this will still trigger all of the reducers to run (and go through the switch statement to see if the action might apply to them) - I believe there is no way around this behaviour. Using reselect however means that your top level component will only receive a prop/state change if there was an actual change that affects that state, rather than triggering a change every time and making React re-render everything, even when the change had no effect because it was somewhere unrelated. (The readme in reselect explains better)

like image 152
luanped Avatar answered Oct 06 '22 14:10

luanped