How to use the useState Hook in React
Tags: react, javascript, webdev, coding
Published: 2024-05-22 06:43:03

#How to use the useState() Hook In React


 A React hook is a special function that allows you to add states and other features to functional components without writing a class.
It was introduced in the 16.8 version of React.

Hooks provides a concise way to handle states in React application.

Examples of these hooks include useState, useEffect, useReducer, useContent, etc.

 In this article, we will be looking at one of the most widely used hooks, useState.

But before proceeding with this article, you need to have:

1. A code editor  (preferably visual studio code)

2. Vite React app running on your IDE
You can check this [article](https://www.npmjs.com/package/create-vite) to proceed with Vite installation In case you don't have it installed.

3. Basic knowledge of HTML, CSS, and JavaScript to understand the concepts behind what we will be explaining in this article.
. Beginner knowledge of React.


##What is useState?

  useState is a react hook that allows you to add states to functional components. The state contains data or information about the component. It can be an array, object, string, number, or boolean.

  When you call the useState, you pass in the initial value for your state. Then React returns an array with two elements. i.e. The current State value and a function to update it.

**useState syntax**:
```reactjs
 const [state, setState] = useState(initialValue);
```
We have the 'state' variable and a function 'setState' to update our current state. Then, the 'initialValue' takes the value of the current state.
 

###How to use the useState hook


-> Import useState at the top level of your components as shown below.
 

![how to import useState Hook](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/t0800wu8eutl1vuk8gy0.png)


-> Invoke it inside a React component: After you have imported useState, then, you proceed to invoke it inside your function.

![how to invoke our state](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/i83orrfwwmvqp8gy6pqm.png)


Inside the function 'myExample', 
- The first value, 'age' is our current state.

- 'setAge' is the function used to update our state.

- useState () sets our current state, Age to 10.

Then, we can now make use of our state inside the function component.


![A code that describes how we used our useState hook](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/pynhltq7koce4mw7zuqz.png)


After declaring our state, then, we proceed to make use of it inside our component.

This **outputs** “My current age is 10.”




###How to update state value


We can update the state by using the updater function (setState) with the new state. Once the component re-renders, then, the state takes the value of the updated state.

This is illustrated in the example below:


![how to update our state](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ssk7jb15907y9dut04j3.png)


In the example above, to update our state, we created a function, “updateAge" and then we used our second element setAge to update our current state.

Then, we invoked our function inside the button elements by using the onClick event. Anytime we click on the button, our components re-render and update our state by adding 1 to the current age.

###Multiple States

In React, we are not limited to having just one state in our components; we can add multiple states.
 Additionally, states can hold different kinds of data types, as shown in the example below.

 
![Multiple States](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ls9c39edkdn3muujmufd.png)

In our example, we have three different states.

-The first state 'name' takes the **string** data type.
-The second state 'age' takes the **number** data type.
-The third state 'hobbies' takes the **array** data type.
Then, we nicely display these states inside our component.

###Conditional Rendering

React allows us to render components based on specified conditions. Just like JavaScript conditionals, where we use if else statements or Ternary operators to set conditions.

In React we can also use these methods and then the short circuit evaluation to specify conditions.

**Using if statement**

The if statement in React works just like it does in JavaScript.
In the example below, we use an if statement to determine age eligibility.


![using 'if' statement to specify condition](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/p1lni2z9s77uz4nf8o2t.png)


**Using short circuit**

 Why do we need the Short Circuit operator?

The reason why we need to use the Short circuit operator and Ternary operators is that we cannot use the ‘If’ statement in all cases because the 'If' statement doesn't return a value and remember, in React, you must always return an expression.

If you run the example below, it will return an error because the ‘If’ statement doesn't return a value, which is the reason why we have to go for the Short circuit operator.


![Inappropriate use of If statement](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ftd8xdrswqay21wtm3iv.png)



The short-circuit operator makes use of the Logical OR operator and the AND operator

**Using the OR operator**: The OR operator checks for the condition specified, if the first condition is falsy, it will return the second value. 

 
_Explanation_
 In the example below, the first condition was false because it was set to an empty string then it returned the second value of 
“John Doe.”

![using OR operator](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/1bt4bg0ynmcnj61tihyl.png)


Essentially, if you change the first condition to true, it will return the first value. “Hello World"


![OR operator](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/wwqqd80sknz9bh4karoi.png)



**Using the And operator &&** : The AND operator works a little bit differently.

 if the first condition is truthy, it returns the second value, and if it's falsy, it returns the first value.


![using AND operator](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/mc6ztx8z29chnd6zii2k.png)

Code Explanation:In the first example above, the first condition was true, then it returned the second value of “John Doe."


-> And operator II example

![AND operator](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/od9ml52pm2y8hotxx4yu.png)


When we change the first condition to false, it returns the first value which is an empty string.
 
 


**Using the Ternary operator**: The Ternary operator uses a question mark and a colon. If the first condition is met, it returns the first value, else it returns the second value.

In the example below, we hide the name “John Doe" by using the Ternary operator to specify a condition.


![Ternary operator](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/6lmby43dbk37ptykul0q.png)

We start by setting the name state to false, then we use the setName inline function to toggle the state between true and false by using the (!) symbol. 
_Hint_: The exclamation mark (!) Is a 'NOT' operator that returns the opposite boolean value of the expression that follows it.

Notice how we added a little bit of inline styling and the onClick handler to handle the click event once the ‘toggle’ button is clicked.

 Once the condition Is true, it shows the name “John Doe" else, it hides the name.



###Conclusion

In this article, we learned about useState Hook in react. We examined how to use the useState, how to update our state, and how to conditionally render our components.
I hope you enjoyed the tutorial.