Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

mapDispatchToProps vs. store.dispatch()

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.

like image 395
kelsonic Avatar asked Dec 12 '16 18:12

kelsonic


1 Answers

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.

like image 161
Jim Bolla Avatar answered Sep 22 '22 15:09

Jim Bolla