Skip to content

Instantly share code, notes, and snippets.

@haohcraft
Last active November 11, 2016 17:46
Show Gist options
  • Save haohcraft/9c957cb75fd493ad1ca735526e751a1a to your computer and use it in GitHub Desktop.
Save haohcraft/9c957cb75fd493ad1ca735526e751a1a to your computer and use it in GitHub Desktop.

The Benefits of Firing Small Actions

Background

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 the State

  • 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.

Benefits of Small Actions

Composability

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.

Easier to Test

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.

Easier to Understand a Complicate Logic

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.

Caveats of Small Actions

Trigger multiple rendering cycle in the app

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.

Way to solve
  • 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.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment