By default mapDispatchToProps
is just dispatch => ({ dispatch })
.
So if you don't specify the second argument to connect()
, you'll get dispatch
injected as a prop in your component.
If you pass a custom function to mapDispatchToProps
, you can do anything with the function.
A few examples:
// inject onClick
function mapDispatchToProps(dispatch) {
return {
onClick: () => dispatch(increment())
};
}
// inject onClick *and* dispatch
function mapDispatchToProps(dispatch) {
return {
dispatch,
onClick: () => dispatch(increment())
};
}
To save you some typing Redux provides bindActionCreators()
that lets you turn this:
// injects onPlusClick, onMinusClick
function mapDispatchToProps(dispatch) {
return {
onPlusClick: () => dispatch(increment()),
onMinusClick: () => dispatch(decrement())
};
}
into this:
import { bindActionCreators } from 'redux';
// injects onPlusClick, onMinusClick
function mapDispatchToProps(dispatch) {
return bindActionCreators({
onPlusClick: increment,
onMinusClick: decrement
}, dispatch);
}
or even shorter when prop names match action creator names:
// injects increment and decrement
function mapDispatchToProps(dispatch) {
return bindActionCreators({ increment, decrement }, dispatch);
}
If you'd like you can definitely add dispatch
there by hand:
// injects increment, decrement, and dispatch itself
function mapDispatchToProps(dispatch) {
return {
...bindActionCreators({ increment, decrement }), // es7 spread syntax
dispatch
};
}
There's no official advise on whether you should do this or not. connect()
usually serves as the boundary between Redux-aware and Redux-unaware components. This is why we usually feel that it doesn't make sense to inject both bound action creators and dispatch
. But if you feel like you need to do this, feel free to.
Finally, the pattern you are using right now is a shortcut that's even shorter than calling bindActionCreators
. When all you do is return bindActionCreators
, you can omit the call so instead of doing this:
// injects increment and decrement
function mapDispatchToProps(dispatch) {
return bindActionCreators({ increment, decrement }, dispatch);
}
export default connect(
mapStateToProps,
mapDispatchToProps
)(App);
can be written as this
export default connect(
mapStateToProps,
{ increment, decrement } // injects increment and decrement
)(App);
However you'll have to give up that nice short syntax whenever you want something more custom, like passing dispatch
as well.