What is the difference between mapDispatchToProps and matchDispatchToProps

Viewed 5397

The title explains the questions.

I am using redux to change state of users to active or in-active users.

In matchDispatchToProps:

function matchDispatchToProps(dispatch){
  return bindActionCreators({selectUser: selectUser}, dispatch);
}

In case of mapDispatchToProps :

const mapDispatchToProps = (dispatch) => ({
    dispatch({selectUser: selectUser})
})

Please explain the difference between these.

4 Answers

I believe you must have heard the term matchDispatchToProps from Bucky's ReactJS & Redux tutorials.

The common name for this function is actually mapDispatchToProps.

But I am not going to say that Bucky made a mistake, because really, this function can be called anything as long as you pass the same name to the second argument of your connect() method.

Example:

const mapDispatchToProps = (dispatch) => {
  return bindActionCreators({selectUser}, dispatch);
}

const mapStateToProps = (state) => {
  return {
    user: state.user,
  }
}

export default connect(mapStateToProps, mapDispatchToProps)(myComponent);

If you aren't mapping state to props, then the first argument can be null

Example:

const mapDispatchToProps = (dispatch) => {
  return bindActionCreators({selectUser}, dispatch);
}

export default connect(null, mapDispatchToProps)(myComponent);

This is a good question to remind us how as developers we sometimes confuse convention with requirement after doing something for such a long time.

Technically, we can call it anything we want, it does not have to be mapStateToProps or mapDispatchToProps, but by convention this is what we call them because it makes our jobs easier when we have this level of consistency.

So the only difference is in the naming convention, these are not built-in functions that do something uniquely specific between each other. In fact, the latter is not conventionally used, I am referring to your matchDispatchToProps, but you certainly can use it if you want to.

Related