Patrick Ivers Patrick Ivers - 1 year ago 42
Javascript Question

Redux: Why not put actions and reducer in same file?

I'm creating an app with Redux and am scratching my head as to why it is best to place actions and reducers in separate files. At least, that's the impression I'm getting from all the examples.

Each action, or action creator, appears to map to a single function that is called by a reducer (inside a switch statement). Wouldn't it be logical to keep these together in the same file? It also makes using the same constant for the action type and switch case easier, as it doesn't have to be exported/imported between files.

Answer Source

From Redux creator Dan Abramov:

Many reducers may handle one action. One reducer may handle many actions. Putting them together negates many benefits of how Flux and Redux application scale. This leads to code bloat and unnecessary coupling. You lose the flexibility of reacting to the same action from different places, and your action creators start to act like “setters”, coupled to a specific state shape, thus coupling the components to it as well.

From the Redux docs:

We suggest you write independent small reducer functions that are each responsible for updates to a specific slice of state. We call this pattern “reducer composition”. A given action could be handled by all, some, or none of them. This keep components decoupled from the actual data changes, as one action may affect different parts of the state tree, and there is no need for the component to be aware of this.

See this conversation on twitter and this issue on github for more information.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download