By default, mapDispatchToProps simply dispatch => ({ dispatch }) .
Therefore, if you do not specify the second argument to connect() , you will get dispatch as support in your component.
If you pass a custom function to mapDispatchToProps , you can do something with a 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 some messages, Redux provides bindActionCreators() , which allows you to do this:
// injects onPlusClick, onMinusClick function mapDispatchToProps(dispatch) { return { onPlusClick: () => dispatch(increment()), onMinusClick: () => dispatch(decrement()) }; }
in it:
import { bindActionCreators } from 'redux'; // injects onPlusClick, onMinusClick function mapDispatchToProps(dispatch) { return bindActionCreators({ onPlusClick: increment, onMinusClick: decrement }, dispatch); }
or even shorter when the prop name names match the names of the creators of the action:
// injects increment and decrement function mapDispatchToProps(dispatch) { return bindActionCreators({ increment, decrement }, dispatch); }
If you want, you can add dispatch there manually:
// injects increment, decrement, and dispatch itself function mapDispatchToProps(dispatch) { return { ...bindActionCreators({ increment, decrement }), // es7 spread syntax dispatch }; }
There are no formal recommendations as to whether you should do this or not. connect() typically serves as the boundary between Redux-aware and Redux-unaware components. This is why we usually feel that we don’t need to introduce both the creators of the related actions and the dispatch . But if you think you need to do this, feel free to.
Finally, the template you are using right now is a shortcut that is even shorter than calling bindActionCreators . When all you do is return bindActionCreators , you can omit the call, rather than doing this:
// injects increment and decrement function mapDispatchToProps(dispatch) { return bindActionCreators({ increment, decrement }, dispatch); } export default connect( mapStateToProps, mapDispatchToProps )(App);
can be written as
export default connect( mapStateToProps, { increment, decrement } // injects increment and decrement )(App);
However, you will have to abandon this beautiful short syntax when you need something more ordinary, such as passing dispatch .