Search code examples
reduxreact-redux

react-redux: when mapDispatchToProps is object, how dispatch action works?


During the usage of react-redux, I came across a confusing point about the mapDispatchToProps, when it is an object instead of function.

For example, in my project, I have the following action creaters:

export const incrementBy2 = () => ({
  type: INCREMENT_REQUESTED_2,
})

And in my component I import the action creator and set it up for mapDispatchToProps:

import { incrementBy2 } from '../actions'
import { connect } from 'react-redux'

// define the Home component, omit the details
const Home = props => ()

// omit the details
const mapStateToProps = state => ()

const mapDispatchToProps = {
  incrementBy2
}

export default connect(
  mapStateToProps,
  mapDispatchToProps
)(Home)

then in the component, I can access the action creator as props.incrementBy2, it also works well in my project.

My confusing point, incrementBy2 is just an action creator, so how and where the dispatch take place?


Solution

  • According to the official docs:

    [mapDispatchToProps(dispatch, [ownProps]): dispatchProps] (Object or Function): If an object is passed, each function inside it is assumed to be a Redux action creator. An object with the same function names, but with every action creator wrapped into a dispatch call so they may be invoked directly, will be merged into the component’s props.

    Also you can follow the source code. There you can check the implementation details.