In a Redux app, when updating State
we would dispatch an action and then the related Reducer
would compute a new version of State
based on the actionType
passed in.
We would come to a point where we need to update multiple part of State
by a function, like within an onClickHandler. In this situation, there are at least two ways to accomplish that.
-
Create a single action to dispatch in the onClickHanlder, and the
Reducer
would be responsible for implement to logic of updating those different parts of theState
-
Create (or using existing) multiple smaller actions within the onClickHandler to dispatch, and the related reducers would react to each individual action accordingly
I am more into the second approach and here are some benefits/caveat I could think of.
Generally speak, addition is much easier then subtraction. When we have small actions/reducers designed only to change a particular small subset of State
, it is possible we can compose different small ones into a bigger one by dispatching them one by one or dispatching a batched one and then let multiple small reducers to compute the updates. More likely, small actions can be easily used by other part of the application.
When action/reducer is small, it means that its logic is simple and concise which is easier to test. And when the case of changing multiple parts of State
comes, we don't have to create a new set of action and reducer to test because those small tasks have been tested.
When dispatching one single action instead, we would put a complicate logic on the Reducer
. It might be not easy to read and understand the code due to its complexity.
Since each action dispatched would update a particular part of State
, each step would make the component(s) go through the its (or their) lifecycle and in all this would happen multiple times by one onClickHanler.
- Use
connect
wisely so that a particular container/component would only update when the connected part of State changes. - On the
Reducer
side, we can combine multiple smaller reducers to a bigger one to hanle complicate computation. - Dispatch a batched action instead. Basically, this try to achieve the point above.