Reputation: 101
Reading many articles and blogposts on this I understand(simplified)
mapDispatchToProps()(
clickHandler: ()=>dispatch(Action)
);
<Component onClick={this.props.clickHandler} />
Does the same as
<Component onClick={store.dispatch(action)} />
Which looks simpler than having all the hassle of using mapDispatchtoProps
I am new to redux and react in general and can't wrap my head around this. Is there an actual necessity to use it or is it just good coding practice?
Upvotes: 2
Views: 397
Reputation: 384
The main idea of connect
with mapDispatchToProps
and mapStateToProps
is to keep you UI components simple and easily reusable. Imagine, if you have 3 applications which have completely different architecture(redux, flux, pure React ContextAPI), but should reuse same UI components. If you incapsulate business logic directly to your components (2. example), then it might be very hard or even impossible to reuse it, because it is attached to some store
(in the place where you use your <Component ... />
).
Just as a side note and good example, how mapDispatchToProps
can make your application clean is clear separation between business logic and UI component.
Example:
You have a Button
component, which is used all over the application. Then you get a requirement that you need to have a logout button in different places of your application. One way would be to create a new regular React component, which will use the Button
component inside and also have some logic.
connect
with mapDispatchToProps
comes to help you and allow to easily create a new LogoutButton
component with attached logic (which also allows you to update the redux state), then whenever you need to have a logout button you simply use LogoutButton
and there will be no need in any extra logic because it's all defined inside mapDispatchToProps
and is already attached to the Button
component.
Upvotes: 1
Reputation: 3547
There isn't an absolute necessity to use mapDisplayToProps
but it will get pretty handy if your application grows.
In your second example you access the store object directly. This is not considered a good coding style because you couple your component to a global object which makes it harder to test the component in isolation or to use it in another context.
Think about each component as an isolated piece of software with the props passed to the component being the only interface to the rest of your application. This won't matter much for small example-like applications but pays off in real-world conditions.
Upvotes: 1
Reputation: 3359
mapDispatchToProps()
is a utility which will help your component to fire an action event (dispatching action which may cause a change of application state)
Upvotes: 0