React — Map Dispatch To Props

F.gicheha
3 min readDec 2, 2020

React Redux Connect:

The connect( ) function connects a React component to the Redux store. This function provides the connected component with the data it needs from the store and the functions it can use to dispatch actions to the store.

Connect accepts two parameters:

  1. mapStateToProps
  2. mapDispatchToProps

These two parameters deal with the Redux store’s state and the dispatch function respectively. In this blog, I will focus on mapDispatchToProps.

What is mapDispatchToProps?

It is the second argument passed to the connect() function. This allows us to specify which actions our component might need to dispatch.

mapDispatchToProps function takes in dispatch function and ownProps(optional) as arguments. Dispatch is what we call to dispatch actions to the store, and ownProps is an object with the props that we passed into components.

mapDispatchToProps returns a plain object that maps dispatch action to the component props. Unlike mapStateToProps instead of returning a piece of state, it returns a function that calls dispatch with an action creator and relevant action data. Here’s an example:

In the example above, we have access to the dispatch because it is passed into mapDispatchToProps( ) as an argument. The object that is being returned has a key of getTrips and a value of the function with dispatch. We can access getTrips by referencing it as a prop: this.props.getTrips.

As stated earlier, connect( ) accepts a function or an object. If we pass it a function, we must incorporate the dispatch. If we pass it an object, the object needs to contain key/value pairs for each action creator we want to become a prop. So in the example above, the object would look like this:

We can use shorthand syntax and write:

We can pass it as a second argument to connect:

In conclusion, mapDispatchToProps( ) allows us to provide specific action creators to our React component.

--

--