Simple Redux Component

Here’s a very basic and traditional Redux connected component. How would you refactor it to using Hooks?

The above is a simple component that toggles the checkbox. To keep things simple, we only have one state, the toggle , which is a boolean.

Toggling a checkbox with Redux

If you know a thing or two about hooks, you probably know hooks expect a functional component. You can’t use hooks with React classes.

Step 1: Refactoring our class component to a functional component

Moving our React component from class to functional is rather simple. All we need to do is the following:

Notice how much shorter this already is. We replaced the class syntax to a simpler functional syntax. We also deconstructed the ui and toggleSwitch props from the arrow function arguments.

If this is new to you, I wrote about this earlier too.

Just to be sure, the toggle still works as intended.

Hooks are usually pre-fixed with a use keyword, like useState or useSelector .

The way we currently read state from our store is via the mapStateToProps and by wrapping our functional component inside the connect HOC.

Step 2: useSelector

Let’s start by reading the state with hooks. We need to import the useSelector from the react-redux package. With the useSelector hook, we can read our state.

Notice we removed the ui argument and instead use the useSelector hook. The first argument of the useSelector is the state of the store.

Here’s how our Toggle component looks now:

Step 3: useDispatch

useDispatch hook lets us fire off our redux actions. Let’s import the useDispatch hook.

Using useDispatch is relatively simple — we save the hook instance under a variable. We can call the dispatch function on any event listeners.

Notice this line:

What we’re doing here is calling our dispatch function with the type constant TOGGLE .

We defined this type in our Redux constants and imported it to the component.

If you want to pass a payload to the dispatcher, do it like we always have.

Here’s how our component should look now:

Congratulations! You successfully refactored from class to using hooks

Just to make sure everything works as intended, let’s test the toggle one more time.

Yup, works as intended.