Reputation: 5937
I am not sure if this is opinion based or is there actually a best practice, but here it goes:
I need to update several data from an action, and I am in a dilemma where I can listen to actions from multiple files in a single reducer, or once an action is done I can dispatch several actions that will be listened by a different reducer each.
As far as my knowledge of redux, listening to actions from multiple files in a single reducer can result in a bloated reducer, which wouldn't be the best way to use the redux. I am not sure if dispatching several actions is any better though. Here is an example:
---------First way:
actions/foo.js
export const doSomething = (data) => {
return(dispatch) => {
dispatch({type: DO_SOME_THING, payload: data})
}
}
reducers/foo.js
case FOO_ACTIONS.DO_SOME_THING:
return {...state, data: action.payload}
reducers/bar.js
case FOO_ACTIONS.DO_SOME_THING:
return {...state, fooData:action.payload}
This is where I listen to the same action from multiple reducers. Or, the second way:
---------Second way:
actions/foo.js
export const doSomething = (data) => {
return(dispatch) => {
dispatch({type: DO_SOME_THING, payload: data})
dispatch({type: DO_SOME_THING_FOR_BAR, payload:data})
}
}
reducers/foo.js
case FOO_ACTIONS.DO_SOME_THING:
return {...state, data: action.payload}
reducers/bar.js
case FOO_ACTIONS.DO_SOME_THING_FOR_BAR:
return {...state, fooData: action.payload}
Is one of the two considered to be the best practice?
Upvotes: 0
Views: 1113
Reputation: 44078
The redux style guide states that you should allow Many Reducers to Respond to the Same Action.
So dispatch one action and react to it in multiple reducers. This for one makes you write actions that are more like "describing events" instead of "setter actions" (this is also recommended, read the whole style guide!). And in addition, depending on the circumstances React might rerender after every dispatch, so dispatching twice might rerender some components twice - which you probably also want to avoid.
Upvotes: 2