Home > other >  Should dispatching an action always cause a change in application state?
Should dispatching an action always cause a change in application state?

Time:12-17

This is more of a best practice question. I'm thinking about a piece of code I observed in a reducer, where it went like this:

if (!state.arrayOfObjects) return;
else {/** add an object to the array of objects/}

Intuitively, I think of an action as something that occurred which enacts some change on the application state. If dispatching an action causes no state change, then I feel that the action most likely should not have been dispatched at all. If there is some condition within the reducer which prevents change from occurring, it probably should have been a condition for the dispatch of the action itself.

On the other hand, maybe the condition within a reducer is one way to create a condition based on a property you don't necessarily want a component to be subscribed to. However, I would think that if the specific action depends on that property, it would be odd for the component to not need the most recent value of that property via subscription in order to determine whether or not it should be dispatched.

CodePudding user response:

In Redux, any number or reducers can react to any action. That includes 0 reducers and 50 reducers.

The Redux Style Guide encourages to Model Actions as Events, Not Setters and to Put as Much Logic as Possible in Reducers.

So while it might not be the common case, it is perfectly fine to have actions that no reducer or middleware reacts to ever - for example for logging puposes or because a reducer might use it in the future. Having actions that reducers react to sometimes, based on some logic, is perfectly normal and 100% fine.

CodePudding user response:

There is a really good article for this question since I can't quiet explain the answer myself. http://jamesknelson.com/join-the-dark-side-of-the-flux-responding-to-actions-with-actors/

  • Related