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.
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.
And here is how it ended up after we refactored it into a functional component using the
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
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.