DEV Community

Zachary Davis
Zachary Davis

Posted on • Originally published at Medium on

Refactoring a Class Component to a Functional Component w/ State Hooks

Introduction

Up until early this year with the release of React 16.8 in February, we as React developers have had to rely on class components to create any components that needed to rely on their own internal state.

State can be used for a variety of different purposes, but in general, it helps us keep track of variables that are only needed within the scope of the component we are using them in or in a component consumed by the component we are in.

Examples

As a simple example, I’ve created a component that consists of a button and an icon (started directly from create-react-app). When the button is clicked, the visibility of the icon is toggled. To accomplish this, we’ll keep track of the visibility in the component’s state.

Here is how we would do it in a class component:

And here is how it ended up after we refactored it into a functional component using the useState hook:

I greatly prefer how much simpler the code is with the useState hooks as compared to the traditional way of handling state in class components, and the process itself was simple.

First, I turned the component into a functional component, removing the constructor and therefore the binding of the handleClick function.

Then, I brought in the useState hook, which rendered the entire handleClick function pointless, so I was able to simply call the setter directly from the onClick prop of the button itself.

And voila! I got rid of 13 lines of code in two simple steps.

There is much less boilerplate when you are given a function that will directly set the state variable for you instead of writing the setState call inside of your own function, and while a 13-line difference might not look huge in this small example, imagine a larger component that needs to keep track of a handful of different variables in its state. The code can begin to get quite long and verbose when you have to write each individual state setter and bind the functions in the constructor.

13 lines per state variable, per component, can really add up!

Hooks are certainly the future of React, and hopefully, I have helped illustrate just why that is in this simple example.

Top comments (0)