Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

mapStateToProps vs mapDispatchToProps [duplicate]

What's the difference between mapStateToProps and mapDispatchToProps arguments to the connect function in react-redux?

like image 487
Leya Varghese Avatar asked Apr 24 '18 05:04

Leya Varghese


People also ask

What is the difference between mapStateToProps and mapDispatchToProps?

mapStateToProps() is a function used to provide the store data to your component. On the other hand, mapDispatchToProps() is used to provide the action creators as props to your component.

Is useSelector the same as mapStateToProps?

The significant difference between them is that mapStateToProps passes down multiple values as props, while useSelector takes the current state as an argument, returns the required data, and stores the returned value as a single variable instead of a prop.

What do mapStateToProps and mapDispatchToProps actually do?

The mapStateToProps and mapDispatchToProps deals with your Redux store's state and dispatch , respectively. state and dispatch will be supplied to your mapStateToProps or mapDispatchToProps functions as the first argument.

Why do we use mapStateToProps?

As the first argument passed in to connect , mapStateToProps is used for selecting the part of the data from the store that the connected component needs. It's frequently referred to as just mapState for short. It is called every time the store state changes.


1 Answers

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); 
like image 50
Shubham Khatri Avatar answered Sep 22 '22 17:09

Shubham Khatri