DEV Community

Uma
Uma

Posted on

How I refactored my code using one of the React Hooks ‘useState()’

A quick introduction of ‘hooks’ according to the reactjs.org docs:

“Hooks are functions that let you “hook into” React state and lifecycle features from function components. Hooks don’t work inside classes — they let you use React without classes.”

There are few points in the reactjs.org docs, as to why use React Hooks. I will link to them below if you would like to learn more:

  1. It's hard to reuse stateful logic between react components
  2. Complex components become hard to understand
  3. Classes confuse both people and machines

Now let's move on to my app where I refactored the class component and used the ‘useState’ hook to manage state. It's recommended by reactjs.org not to refactor old projects with hooks, and to instead use hooks in new projects. You can find out why here I was curious while going through the document linked in the previous sentence, so I decided to try it out in an existing application anyway. Here I was trying to add a Like feature in the app so I created a class component like so:

Alt Text

Above is a LikeButton class component that has a default state set to zero. In the render function, there is a button called Likes returning the default state. To update the state each time users click on the like button we have a handleClick function that updates the current state by using the built-in function setState. Now we can use this component wherever we want to add a Like button. In my case I added it in the job listing like so:

Alt Text

In the browser it looks something like this:

Alt Text

Now let’s refactor this using the ‘useState’ hook. Remember ‘hooks’ can’t be used in class components, they can only be used in functional components. Don’t forget to check the links provided at the beginning of this article to know why to use hooks. Now for the refactoring, first we have to convert the class component to a functional component to be able to use the ‘useState’ hook. Then import ‘useState’ from React and implement it like so:

Alt Text

Above on line 4, we have the const variables ‘like’ and ‘setLike’ where ‘like’ creates a piece of state that is set to a default value of the 0 in the parenthesis after useState and ‘setLike’ is used for updating that state value, similar to setState. Now to update that state all that has to be done is, inside the ‘onClick’ function, create an arrow function that returns setLike, which increments ‘like’ by 1 each time users click on the button. That's all. You can compare these two components and figure out which one has less code and more readability. Some prefer class components, some prefer functional so it really is your preference of which to use.

Top comments (0)