Reputation: 2635
Looking at examples of how to use mapDispatchToProps
most examples follow the following pattern, a function that returns an object with dispatch
as an argument:
const mapDispatchToProps = (dispatch) => {
return({
someFunc: (arg) => {dispatch(someFunc(arg))}
})
}
My question is, if all my actions are using thunk
, meaning they all have access to dispatch
anyway, why would i need to use the above example for mapping functions to props in my containers
?
After experimenting i've figured out another way that seems to work, however im not sure if this is best practice...
Main.jsx
import * as mainActions from '../actions/mainActions'
import * as menuActions from '../actions/menuActions'
const actionsToMap = {...mainActions, ...menuActions}
export default connect(mapStateToProps, actionsToMap)(Main)
Is there anything wrong with this approach?
Upvotes: 0
Views: 3444
Reputation: 4971
Separating the concerns is a good idea and in almost all apps it would be a good idea to use Action Creators (which is what you're doing in the second example) as oppose to use plain objects (as in the first).
There are several benefits:
It's not just me saying this, the Redux docs covers it here: https://redux.js.org/recipes/reducingboilerplate#action-creators
That being said, they do also say that plain objects might be enough, but considering how simple action creators actually are it's probably worth making your work extensible in almost all cases.
Upvotes: 0
Reputation: 1823
Both approaches are correct and you can also use bindActionCreators when you want to pass some action creators down to a component that isn't aware of Redux, and you don't want to pass dispatch or the Redux store to it. Technically, that's the only use case for it.
Pulling it from the documentation, mapDispatchToProps
can be a function or object.
I think your first approach is good for documentation as one can easily see the signature of the action creators you're using in your component without having to navigate to the action creator file. Other than that, I'm fine using objects(your second approach) in most cases.
Hope this helps!
Upvotes: 1