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.
If you do not supply your own mapDispatchToProps function or object full of action creators, the default mapDispatchToProps implementation just injects dispatch into your component's props.
You can dispatch an action by directly using store. dispatch(). However, it is more likely that you access it with react-Redux helper method called connect(). You can also use bindActionCreators() method to bind many action creators with dispatch function.
Redux uses a "one-way data flow" app structure When something happens in the app: The UI dispatches an action. The store runs the reducers, and the state is updated based on what occurred. The store notifies the UI that the state has changed.
There are two ways to dispatch actions from functional components: Using mapDispatachToProps function with connect higher order component, same as in class based components. Using useDispatch hook provided by react-redux . If you want to use this hook, then you need to import it from the react-redux package.
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?.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With