Is it more efficient to use mapDispatchToProps
inside a ponent 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.
Is it more efficient to use mapDispatchToProps
inside a ponent 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.
1 Answer
Reset to default 5It is generally remended 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.