React Redux store calculations in the reducer or action-creator?

Viewed 994

I'm learning React and Redux by creating an app which contains an array of time-based data: allowed time, and elapsed time.

[1] : {
  time: 10,
  elapsed: 0
},
[2] : {
  time: 15,
  elapsed: 0
},
[3] : {
  time: 20,
  elapsed: 0
}

If any items go over schedule, I want to recalculate the times for subsequent items. E.g. item 1 is allowed 10 seconds, but if item 1 takes 12 seconds I want to make up that time from items 2 and 3.

[1] : {
  time: 10,
  elapsed: 12
},
[2] : {
  time: 14,
  elapsed: 0
},
[3] : {
  time: 19,
  elapsed: 0
}

Where should I perform this calculation? I feel like the easiest place to do this would be the reducer, but I also think that reducers should be as simple as possible? Is that correct?

So should the calculations go in the action-creator, and then a new items array passed to the store?

3 Answers

Quoting from the original Redux Documentation.

There's no single clear answer to exactly what pieces of logic should go in a reducer or an action creator. Some developers prefer to have “fat” action creators, with “thin” reducers that simply take the data in an action and blindly merge it into the corresponding state. Others try to emphasize keeping actions as small as possible, and minimize the usage of getState() in an action creator. (For purposes of this question, other async approaches such as sagas and observables fall in the "action creator" category.)

There are some potential benefits from putting more logic into your reducers. It's likely that the action types would be more semantic and more meaningful (such as "USER_UPDATED" instead of "SET_STATE"). In addition, having more logic in reducers means that more functionality will be affected by time travel debugging.

IMO this should be done in the reducers.

The action should not know what will be the effect of the dispatched action, the reducer is the one in charge of returning the new state as a effect of the dispatched action.

Related