How I reduced the code in my Redux app by using Redux Hooks.

Here’s how you can simplify the Redux bindings in all of your components to help reduce your React Redux boilerplate.

Sunil Sandhu
Nov 15, 2019 · 6 min read

I recently wrote an article that compared the exact same app built with React and again with React + Redux.

The code for the app that had Redux used connect() bindings to hook up our components to our store. This meant that we had things such as mapStateToProps and mapDispatchToProps adding several lines of code to each of our container* components.

Anyway, a couple of people mentioned that I should have used Hooks to simplify those Redux bindings.

Now please bear in mind that this isn’t an article designed to preach that you should go and rewrite all of your previous Redux code — because you definitely shouldn’t be wasting time rewriting something if it already works perfectly. However, I do think it would be a good idea to shed some light on what your code would look like if you swapped out the old Redux bindings for the new Hooks-based ones. That way you can look to leverage these new bindings for the next new project you find yourself working on.

Let’s start!

Now our To Do app is pretty simple, so fortunately we only had one file that needed to use our Redux connect() bindings. That file also didn’t have to pull in too much stuff from our Redux store/actions. However, the file still looks quite messy, as we can see from the image below:

Our app when using connect() bindings
Our app when using Redux Hooks

useSelector()

useSelector()

useDispatch()

useDispatch()
Our dispatch functions
An alternative way to writing our dispatch functions
importing actionTypes
importing appActions

Props

How we passed in our props to the ToDo component
An alternative approach to passing in our props.

So there we have it!

We’ve reduced some of the boilerplate in our Redux app. Besides the Redux mental model, the boilerplate can be a concern for new devs to wrap their head around. Hopefully Redux Hooks can help to reduce the amount of head wrapping. We no longer have to worry about wrapping our components inside of connect() Higher Order Components anymore!

A screenshot of the app but cropped a bit so that we can use it for the featured image thing

JavaScript in Plain English

Learn the web's most important programming language.

Sunil Sandhu

Written by

Software Engineer, Editor of JavaScript In Plain English (JSIPE)

JavaScript in Plain English

Learn the web's most important programming language.

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade