In this article, I will try to explain how you can use Redux with React Hooks.

React Redux gave support for Hooks in version 7.1 which was released on the 11th of June, 2019. It means that you can use Redux with Hooks in your functional component instead of using connect higher-order components (HOC).

What Are Hooks?

Just to refresh a little about Hooks, Hooks were introduced in React version 16.8 and they allow you to access state and life cycle methods in functional components.

Let’s have a look at an example.

A React class component like this:

In this article, I will try to explain how you can use Redux with React Hooks.

React Redux gave support for Hooks in version 7.1 which was released on the 11th of June, 2019. It means that you can use Redux with Hooks in your functional component instead of using connect higher-order components (HOC).

What Are Hooks?

Just to refresh a little about Hooks, Hooks were introduced in React version 16.8 and they allow you to access state and life cycle methods in functional components.

Let’s have a look at an example.

A React class component like this:

Can be written as a function component using Hooks like this:

If you want to explore Hooks more, I would suggest you go through the detailed docs on Hooks.

Back to Business

The original purpose of this article is to explain how we can use Redux with Hooks.

React Redux now offers useSelector and useDispatch Hooks that can be used instead of connect.

useSelector is an alternative to connect’s mapStateToProps. You pass it a function that takes the Redux store state and returns the state you need.

useDispatch replaces connect’s mapDispatchToProps. All it does is return your store’s dispatch method so you can manually dispatch actions.

Enough theory? Alright, let’s have a look at a real-time example in which we will convert a React component that uses connect into one that uses Hooks.

Using connect:

Now, with the new React Redux Hooks instead of connect:

As you can see, code is precise and fewer lines mean better performance, it’s easier to read, easier to understand, and of course, easier to test.

Another benefit of not using the higher-order component is that you no longer get this “Virtual DOM chaining”:

Now you have the basics of Hooks and how to use them with Redux, time to get your hands dirty with the detailed documentation.

Did you learn something new today? Comments and feedback always make the writer happy!

Published On: March 1st, 2020 / Categories: Blogs /