Get “hooked” on these Redux hooks

Sean Dever
3 min readJul 29, 2020

Redux out of the box is a little hard to follow for those just learning the library for the first time. You have all these function like connect, mapStateToProps, mapDispatchToProps and all these other things that are kind of hard to understand for the first few couple time you play around with it. With React’s implementation on the “hooks” API, it’s given a lot more flexibility with things we can do with react. Redux has done just that and made some custom hooks that make it a lot easier to read and understand the flow of Redux.

How we did things before

Let’s take a simple counter as an example:

Here we have our Counter component that on button click will hit our increment or decrement function, those functions receive their props from the mapDispatchToProps which checks our reducer to see if we have a type of “UPDATE” if it does we want to change the property of our amount state we have stored there to the value we pass in(in these functions case, add or reduce by 1). We then have access to this state through our mapDispatchToProps where we are about to tap into our count state and use it as props to display the current state. We are then able to do all these things with the connect function at the bottom that allows us to even connect to our Redux store.

How we do things now

with Redux hooks we have useSelector and useDispatch functions to do exactly the same thing but in a lot less code!

useSelector

useSelector here is basically doing the same thing as our mapStateToProps. We are able to tap into our state and accessing the count from our state to use to display the current count in our h1 tag.

useDispatch

I’m sure you can guess what the next one is going to do. Yup you got it, it has the same functionality as mapDispatchToProps. Here it’s going to tap into our Reducer, look for the case where the type is equal to “INCREMENT” or “DECREMENT” and execute the following action(in this case add or subtract by 1).

All the same functionality in half the code! Hope you find great use out of this tool like I am. Happy Coding!

--

--