DEV Community

loading...

Redux Hooks

Kyle Trahan
Full Stack Software Engineer
・2 min read

Recently I decided I would take my first React-Redux project and refactor it to see how far I have progressed since being in Flatiron School. When I opened up my code it was a bit overwhelming to see how disorganized it felt considering how happy I was with it when I originally wrote it. I was using class components and passing my Redux store state around with the connect wrapper. I figured I would take a shot at refactoring to use hooks everywhere instead. This required transitioning all of my class components into functional components. This was no small task but I was eventually able to complete it.

Funnily enough I actually stored all of my reducers inside of my index.js file, don't ask me why. So I also went through the process of reorganizing my file structure so that it would be easier to come back to this project and not feel so lost.

Then I moved on to learning about the different hooks Redux uses. The two I will be focusing on are useSelector and useDispatch. It might just be a sign of the progress I have made since first learning Redux, but I found using hooks was less complicated then when I originally learned how to use the connect wrapper. So here we go, first up is useSelector, this is the equivalent of mapStateToProps. Its very simple to use and it will give you access to your store state. It looks like this

const thingIWant = useSelector( state => state.thePieceOfStateIWant)
Enter fullscreen mode Exit fullscreen mode

The useSelector function is very smart in that whenever a new dispatch is sent it won't automatically re-render. It will check to see if the value has changed and re-render only if the value has changed.

The other hook I wanted to mention was useDispatch. It is equivalent to mapDispatchToProps. This hook will return a reference to the dispatch function. It allows you to send a dispatch to the store and update your state there based on the action.type. Its fairly simple to put into action as well.

const dispatch = useDispatch()
Enter fullscreen mode Exit fullscreen mode

Then you can use this variable to send dispatches to your store like so:

dispatch({ type: "WHATEVERTYPE", payload: infoToUpdate})
Enter fullscreen mode Exit fullscreen mode

Thats all there is to it, you can set up your reducers the same way you normally would using connect but now you can type out less code in order to gain access to and update your store. I'm really enjoying the process of updating my project and seeing how far I have come. I am still working through quite a lot of things and can't wait to see where the project ends up. Have a great day!

Discussion (0)