DEV Community

Gloria Tejuosho
Gloria Tejuosho

Posted on

How to use the useState Hook in React

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 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:

 const [state, setState] = useState(initialValue);
Enter fullscreen mode Exit fullscreen mode

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

-> 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

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

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

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

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

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

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

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

OR operator

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

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

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

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.

Top comments (1)

Collapse
 
henriking201 profile image
henriking🦁

Nice 👍