Skip to content

Akhila Ariyachandra

Use Hooks in React Redux

React, Redux, Hooks1 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.

Getting Started

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 mapStateToProps in connect().
  • useDispatch - Allows us to dispatch out redux actions. This hook will be used to replace mapDispatchToProps in connect().

Refactoring the Controls Component

First lets remove the props, connect() Higher Order Component and mapStateToProps and mapDispatchToProps.

Then we need to import the two hooks from react-redux.

To get the redux state, we need to use useSelector. 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 getUser action.

Just change all actions to run inside the dispatch function.

Refactoring the Display Component

We need to refactor the Display component the same way we did the Controls component.

  1. Remove all the connect() Higher Order Component related code.
  2. Import useSelector and useDispatch.
  1. Declare the user state using useSelector.
  1. Declare the dispatch function using useDispatch.
  1. Change all Redux action to be called inside the dispatch function.

In the end the code for the Display component should look like this.

Wrap Up

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! 😊