React-Redux: Utilizing ‘connect’ when accessing dispatch

Brendan Fitzgerald
3 min readJun 7, 2021

--

Between `mapStateToProps`, `map`DispatchToProps`, `dispatch`, `combineReducer` and all the other extra tools that come with using Redux, it’s easy to get overwhelmed. Thankfully, we can utilize our `connect` function from `react-redux` to clean up our code to make things simple to read. Let’s take the following example:

We are working with a simple application creating ‘Lists’ and adding ‘Todos’ for those lists. At this point in our application, we are looking at our `ListForm.js` attempting to add a list to our redux store. Our form looks like this so far:

Upon submission of our form, the `handleSubmit` function will take our list, and dispatch our list object to our reducer, which will handle the `ADD_LIST` action, update our state, and the use client-side routing to render the `/lists` page without needing to refresh. This way allows us to access dispatch directly as a prop. However, if we want to stick to good practices when dealing with separation of concerns, we can utilize Redux’s `mapDispatchToProps` function to pull out that dispatch function. Refactoring would now look like this:

Refactored above, we can easily call on our addList action that we have created inside our `mapDispatchToProps` function, passing in our list object as an argument. Don’t forget, when connecting your redux store with `{ connect } from ‘react-redux’`, the connect function requires that `mapStateToProps` be it’s first argument. We aren’t utilizing `mapStateToProps` here in this component, so we want to pass `null` as that first argument. Speaking of connect, what a fantastically helpful function! Connect can determine if the items you pass in as arguments are functions or objects — which means we can utilize another great way to invoke our dispatch function! Take a look:

We are able to pull out the `addList` action into an Action Creator folder, and define our action there (remember — separation of concerns!) Once you import that `addList` action creator into your `ListForm` component, we can now clean up so much of our code, and allow the connect function to take the return value from our `addList` action (returns an object) and call the dispatch function on that object for us. Magic! All cleaned up, we get a nice and clean section of code:

You’ll notice that we can even utilize destructing on our `addList` action when using our `connect` function. Happy coding!

--

--

Brendan Fitzgerald
Brendan Fitzgerald

Written by Brendan Fitzgerald

0 Followers

Living in the Pacific Northwest with my loving wife, and beginning my career as a Software Engineer.

No responses yet