00500005
00500005

Reputation: 4067

Why separate actions + reducers In Redux?

I've seen the argument for separating actions and reducers because they have a many-to-many relationship.

I don't think that actually applies in Redux though. Because there's only 1 datastore, actions to reducers should be 1-to-many.

Typically reducers apply to a specific change for a specific datastore.

MY_ACTION = "MY_ACTION"
function reducer(state, action) {
    switch(action.type) {
        case MY_ACTION: // stuff with my action to create new state
        default: return state
    }
}

We can combine multiple reducers with combineReducers so why not define the handler for an action with the action itself.

For instance

class Action {
    constructor(type) {
        this.type = type
        this.handlers = []
    }
    add_handler(handler) {
        this.handlers += handler
    }
    get_reducer() {
        reducer = combineReducers(this.handlers)
        return (state, action) => {
            if(action.type == this.type) {
                return reducer(state, action)
            }
            return state
        }
    }
}

With the "ducks" pattern, we end up putting the main reducers in the same module as the action declaration.

Is there any reason to keep reducers + actions separate with redux?

Upvotes: 9

Views: 1896

Answers (1)

Andrew Winterbotham
Andrew Winterbotham

Reputation: 1010

The main reason for separating the action creators from the reducer function is that the reducer function must be a pure function. If you wanted to do something in an action creator, like an asynchronous API call for instance, then you could not put this in the reducer. There's a great explanation on this here.

Upvotes: 3

Related Questions