Transitioning from React Class Components to React Hooks; Using Redux with React Hooks

source

This article has been a long time coming. I have been meaning to write this for a while now and somehow, I have been procrastinating but I finally overcame and here it is!

Disclaimer: This article assumes that you have already been working with React Class Components.

With the introduction of React Hooks, React functional components can now do a lot more. We can now access lifecycle methods from React functional components and in a more concise manner.

The example below is written with a class-based approach and just shows a very simple component that displays age from the state on the component mount.

Below is the same code but written with a functional component utilizing React Hooks. Neat right?

The first thing you notice with the example above apart from the fact that your code is shorter is that you can now access your lifecycle method using useEffect and set state using useState. Elegant!

I like to use Redux for state management in React and with the introduction of hooks, I was sceptical about what that meant for me but with the release of version 7.1, we get support for Reach Hooks so yay! and it’s yay X10 when I found out how easy it is to implement.

How to access your Redux state using React Hooks

Do you remember how with class components, you had to do something like this to be able to access the redux state and actions?

Well, with Hooks, those days are gone!

With React Hooks, you get useDispatch and useSelector and these two replaces the mapDispatchToProps and mapStateToProps that you get when using connect in Class components and so the code above translates to this

The useDispatch hook gives you access to the dispatch function from which you can easily call your function.

While all these are exciting, there is nothing wrong with using the React class component if you still really want to but you might just want to give Hooks a chance and I promise, you won’t hate it.

I eat. I read. I write. I code. Never in that order