Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why separate actions + reducers In Redux?

Tags:

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?

like image 362
00500005 Avatar asked Apr 22 '16 16:04

00500005


1 Answers

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.

like image 86
Andrew Winterbotham Avatar answered Oct 17 '22 19:10

Andrew Winterbotham