Is it more efficient to use mapDispatchToProps
inside a component to call actions or is it more efficient to use store.dispatch
inside action creators?
mapDispatchToProps
example:
// Component
import React from 'React';
import { connect } from 'react-redux';
import { defaultAction } from './actions';
class MyComponent extends Component {
onClickHandler() {
this.props.dispatch(defaultAction());
}
render() {
return (<div onClick={this.onClickHandler.bind(this)} />);
}
}
function mapDispatchToProps(dispatch) {
return { dispatch };
}
export default connect(mapDispatchToProps)(MyComponent);
// Actions
import { DEFAULT_ACTION } from './constants';
export function defaultAction() {
return {
type: DEFAULT_ACTION,
};
}
store.dispatch()
example:
// Component
import React from 'React';
import { connect } from 'react-redux';
import { defaultAction } from './actions';
class MyComponent extends Component {
onClickHandler() {
defaultAction();
}
render() {
return (<div onClick={this.onClickHandler.bind(this)} />);
}
}
export default MyComponent;
// Actions
import { DEFAULT_ACTION } from './constants';
import store from './store';
export function defaultAction() {
store.dispatch({
type: DEFAULT_ACTION,
});
}
My guess is that it's more efficient to use mapDispatchToProps
instead of importing the entire ./store
to dispatch actions.
It is generally recommended to use dispatch
as provided to you via mapDispatchToProps
, and not to couple your action creator methods to your store singleton. Here's some in depth discussion about it.
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