user6399242
user6399242

Reputation:

what is the use of 'mapStateToProps' and 'mapDispatchToProps' in Redux?

I can't understand the actual use of mapDispatchToProps, mapStateToProps so please explain with example.

Upvotes: 5

Views: 2612

Answers (1)

Amit Mundra
Amit Mundra

Reputation: 166

mapDispatchToProps and mapStateToProps, are two API's.

mapStateToProps provides the store's current state object, using this we can filter and use the required part of state. We can also provide ownProps parameter which contains Component's parent supplied arguments. e.g:

   const mapStateToProps = (state, ownProps) => {
     return state;
   }

mapDispatchToProps lets functions available inside our component's. So with actionCreators we can supply functions that could be used directly without dispatching them inside our Component e.g:

const mapDispatchToProps = dispatch => {
return {
    login1: bindActionCreators(login, dispatch)
}
}

here login supplied to bind function is imported as * from an actions fil. e.g import login as * from 'filename'

Now Connect is an another API which is given by react-redux which provides the real glue and make things working e.g:

  export default connect(mapStateToProps,null,mapDispatchToProps)(Login)

here Login is the Component(Class) to which we need to map to.

Hope this might clear, the difference feel free to ask if any more dobuts

Upvotes: 2

Related Questions