Pongsakorn Semsuwan
Pongsakorn Semsuwan

Reputation: 387

What's the use of mapDispatchToProps when we can just use this.props.dispatch to dispatch action

I've been using @connect annotation for some time and decide to switch to mapStateToProps and mapDispatchToProps.

I can mapStateToProps to map store to component's props fine but wondering what's the point of mapDispatchToProps when I can just call this.props.dispatch( xxx ) anywhere.

I also see some react repos and they also do not use mapDispatchToProps

Sorry if it sounds like a beginner question.

Upvotes: 18

Views: 2591

Answers (1)

markerikson
markerikson

Reputation: 67469

Yes, you can certainly use props.dispatch() directly in a component. However, that component now "knows" that is part of a Redux application, because it's explicitly trying to "dispatch" things.

On the other hand, if you consistently use action creator functions, now the component is just calling things like this.props.doSomeThing(). It doesn't actually "know" that it's in a Redux app, and is more reusable as a result.

I just answered a similar question at When would bindActionCreators be used in react/redux? , and wrote a longer blog post on the topic at Idiomatic Redux: Why use action creators?.

Upvotes: 13

Related Questions