Intro to using the State Hook in React

Caitlin R
3 min readJul 19, 2021

The State Hook is a very important hook in react for creating functionality.

In this blog post, we will demonstrate how to use the useState hook in react to create functionality for a simple Like button in our simple Hello app:

In this example, we start with a very simple app with one component, the Person component. It displays information found in the people array, as well as a Like button for each of those elements:

Right now the Like button doesn’t have any functionality. We want it to add likes every time the user clicks it, and since this is something that changes based on user input, it is smart to use the State hook.

To do that, in our Person component, the first thing we need to do is import the hook from the React library, as seen in line 1 below:

Next, we will use our hook within our function component to declare a new state variable, which we’ll call likesCount, and the setter function, which we’ll call setLikesCount. We will set the initial default value of likesCount to 0 (see line 5 below).

Then, we will add the {likesCount} variable to our JSX in line 10, so it will display our likesCount. Those will now be displayed as 0 on the webpage since we set our default to 0 in line 5.

Now the last step is to write the callback function in line 11 that is activated every time the user clicks the like button, to add an additional like to our likesCount. This is where we will define our setter function from line 5, setLikesCount. See below:

Now, when we click the like button, the likesCount increases by 1!

Every time the user clicks a Like button, the likesCount for that person goes up:

So that is a simple explanation and example of how to use the State hook in React to create events with variables that change based on user input! Learn more about the State Hook on MDN!

--

--