Redux: the Connect Function

The connect function creates container components with Redux. It takes two functions as arguments. The first is mapStateToProps, which, as you may have already guessed, maps the state to the props. In other words, it exposes the application state to the component via props. The second argument is mapDispatchToProps. It determines which actions to expose to props.
export default connect(
    mapStateToProps,
    mapDispatchToProps
)(SomePage)

mapStateToProps

Again mapStateToProps, makes the state available to the component via props. It is a function that takes state and props as arguments and returns the state.

function mapStateToProps(state, props){
    return { appState: state.someReducer }
}

mapDispatchToProps

While MapDispatchToProps  is an optional argument, it is quite useful. It is a function that takes dispatch as an argument and returns the available actions. It determines which actions to expose to props and you can go about this three ways:
1. Ignore it and use dispatch directly in your component
this.props.dispatch(loadCourses())
2. Manually wrap dispatch for each action..
function mapDispatchToProps(dispatch){
    return {
         loadCourses: () => { dispatch(loadCourses }
    }
}
3. Use bindActionsCreators
This is a convenience method that wraps all of your actions with dispatch.
function mapDispatchToProps(dispatch){
    return { actions: bindActionCreators(actions, dispatch) }
}

Leave a Reply

Your email address will not be published. Required fields are marked *