Convert Redux to Hooks
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 11th June 2019. It means that you can use Redux with Hooks in your functional component instead of using a connect higher order component (HOC).
What are Hooks?
Just to refresh a little about hooks, hooks were presented in React version 16.8 and it allows you to access state and life cycle methods in functional components.
Let’s have a look at an example.
React class component like this:
Can be written as a function component using Hooks like this:
Back to Business:
The original purpose of this article is to explain how we can use Redux with Hooks.
React Redux now offers use selector and use dispatch hooks that can be utilized as opposed to associating.
use selector is an alternative to connect’s mapStateToProps. You pass it a function that takes the Redux store state and returns the state which you need.
useDispatch replaces connect’s mapDispatchToProps. All it does is return your store’s dispatch method so you can manually dispatch activities.
Enough theory? All right let’s have a look at a real-time example in which we will convert a React component that users 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, fewer in lines mean better performance, easier to read, easier to understand and of-course easier to test.
Another advantage of not using the higher-order component is that you no longer get this “Virtual DOM chaining”:
Did you learn something new today? Comments and feedback always make the writer happy .