Building a Like and Dislike Widget with the React State Hook

Sam Hall
3 min readNov 7, 2021

How to build a simple like and dislike widget with the State Hook {useState}.

Do we like it?!?!

Here is a brief tutorial on how to build a very simply styled like and dislike widget for your React application using the React State Hook, {useState}.

Hooks are essentially functions unique to React that let you “hook-into” specific features of React’s framework. For instance, the React State Hook allows one to add state to a given component. Assigning a variable state requires an initial state, and the “set state” function that updates the initial state. That’s a lot of states! Simply, we define a variable like so:

In my example, I set two state variables: one indicating the number of likes on a photo, and the other indicating the number of dislikes:

“likeNumber” is the variable for the initial state of likes, currently zero, and “dislikeNumber” indicates the same. These state variables will remain at zero unless we writes some code to affect change on the variables.

In the HTML portion of our App component, we need to attach click functions to our button elements to ensure that when a particular button is clicked, the integer value of our state variable increases once per click. It should look something like this:

Our App component’s HTML and what displays on the page.

Here, the “onClick” function is redirecting each button click to a function defined above… seen below:

handleLikeClick and handleDislikeClick both take the initial state variables for likeNumber and dislikeNumber (which are both 0), and uses the function to reset the state of the variable to whatever number it currently is, plus one. So theoretically, each time we hit either button, the number displayed by the <h3> tags on the page should rise incrementally per click:

The end result!
A clearer screenshot of the code.

Sources and Further Reading

Examples made with React - CodeSandbox

--

--