What's the Difference between mapstatetoprops and mapdispatchtoprops

Leya Varghese picture Leya Varghese · Apr 24, 2018 · Viewed 22k times · Source

What's the difference between mapStateToProps and mapDispatchToProps arguments to the connect function in react redux ?? Can anyone give a suitable explanation with examples

Answer

Shubham Khatri picture Shubham Khatri · Apr 24, 2018

mapStateToProps is a function that you would use to provide the store data to your component, whereas mapDispatchToProps is something that you will use to provide the action creators as props to your component.

According to the docs:

If mapStateToProps argument is specified, the new component will subscribe to Redux store updates. This means that any time the store is updated, mapStateToProps will be called. The results of mapStateToProps must be a plain object, which will be merged into the component’s props.

With mapDispatchToProps every action creator wrapped into a dispatch call so they may be invoked directly, will be merged into the component’s props.

A simple example would be

function mapStateToProps(state) {
  return { todos: state.todos }
}

function mapDispatchToProps(dispatch) {
  return { addTodo: bindActionCreators(addTodo, dispatch) }
}

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