With the release of React Redux 7.1.0, we can now use hooks, which offer a modern approach to working with React. Hooks help us write less code while achieving the same functionality. This means we can build our applications faster and more efficiently.
If you’re new to hooks, check out my earlier tutorial, Demystifying React Hooks. It will give you a solid understanding of how hooks work.
Refactoring a Redux Component to Use Hooks
Let’s start with a simple Redux component that uses the traditional class-based approach. We’ll refactor it to use React hooks.
Step 1: Convert to a Functional Component
We’ll start by converting the class component to a functional component. This change makes the code shorter and more readable:
In this version, we use a functional component instead of a class. We also directly destructure ui and toggleSwitch from the function parameters.
Step 2: Use useSelector to Access State
To read the state from Redux, we use the useSelector hook:
Here, useSelector replaces mapStateToProps. It provides access to the Redux state directly.
Step 3: Use useDispatch to Dispatch Actions
To dispatch actions, we use the useDispatch hook:
With useDispatch, we can call dispatch to send actions. In this case, we dispatch the TOGGLE action when the checkbox is toggled.
Congratulations! You have successfully refactored your component from a class-based approach to using hooks. Be sure to test the component to make sure it works as expected.