Use Hooks in React Redux
Posted on 10th November 2019
4 min read
In my previous post I went through setting up Redux in a React app. Since then I learnt about using hooks as an alternative to the
connect() Higher Order Component. In this post we will refactor the app we made in the previous post to use the Redux Hooks.
Before we start refactoring let’s check out the two hooks we are going to use.
useSelector- Allows us to get the state from the Redux store. This hook will be used to replace
useDispatch- Allows us to dispatch out redux actions. This hook will be used to replace
Refactoring the Controls Component
First lets remove the props,
connect() Higher Order Component and
Then we need to import the two hooks from react-redux.
To get the redux state, we need to use
useSelector needs a function as an argument where the redux state is the parameter and the return object is the state we need, similar to
mapStateToProps. So use
useSelector to declare the user inside the component.
The above line of code can be shortened to the following.
To call the redux actions, we need to declare the dispatch function in the component using the
useDispatch hook. After that we can call out redux actions inside the dispatch function like we did in the
Just change all actions to run inside the
dispatch function like this.
In the end the Controls component should look like this.
Refactoring the Display Component
We need to refactor the Display component the same way we did the Controls component.
- Remove all the
connect()Higher Order Component related code.
- Declare the user state using
- Declare the dispatch function using
- Change all Redux action to be called inside the
In the end the code for the Display component should look like this.
This is a sample of the setup we just did. If you think you missed something, feel free to check out the code.
If you want to learn more about the hooks in react-redux, please check out the official documentation here.
If you found this post helpful please make sure to share it! 😊
Leave a Reaction below!!! (No login required)