useState in React

Learn via video courses

Overview

UseState in React JS is one of the react hook that is used to create a variable in a react application that affects the state of the react application. Whenever some modification is done on a useState variable, the state of the application gets re-rendered. In this article, we will discuss this hook in detail.

Hooks and Function Components in React

Hooks in React

Hooks are the react function that allows us to use or modify the state of a react application. As per React's official documentation, A Hook is a special function that lets you “hook into” React features. The latest version of React i.e. React 18 has 15 hooks among which, the useState hook, useEffect hook, and the useRef hook are very popular among developers.

Function Components in React

React application allows us to write different features of the application in the form of components. There are two ways to write the definition of a component i.e. Function Component and Class Component. The syntax of the function component is written below.

React Function Component can also be written in the form of an arrow function. The syntax for this is written below.

React hooks can be used inside the React Function Components.

What is useState() in React JS?

UseState is one of the react hook that is used to create a variable in a react application that affects the state of the react application. Whenever some modification is done on a useState variable (for example the useState variable value changes), the state of the application gets re-rendered.

Syntax of useState()

The useState in React JS can be used in the React Function Component as well as in React Class component (Using Render() and setState() functions).

1. Reaction Function Component

Given below is the syntax of useState in React JS inside a React Function Component.

2. React Class Component

React Class Component uses functions like Render() and setState() to define a state variable. Given below is the syntax for defining a useState in React JS in a React Class Component.

When to Use UseState in React?

useState in React JS is used to store data in the form of a string, integer, objects, float, etc. The most important property of the useState in React JS is that when the value of the variable changes, the component in which the state variable was declared gets re-rendered.

For example, if we want to build the quantity counter of an item inside the cart of an e-commerce website, we can use useState in React JS to declare a counter variable. On clicking the 'plus (+)' or 'minus (-)' button, the value of the counter must increase and decrease by 1 respectively. As soon as the value of the counter variable gets changed, the page will get re-render and we will see an updated value of the counter on our page.

Given below is the code for the above situation.

This is what our component looks like. The plus button increases the quantity and the minus button decreases the quantity.

use of usestate

Using Multiple State Variables in React

Multiple state variables can be defined either individually, or they can be merged into a single state object. For example, if we want to maintain two variables named 'state1' and 'state2', the syntax for both ways is written below.

1. Declaring the states individually

2. Declaring a state object for both the state variables

State Asynchrony

In React, the changing/modification of a state (for example using a setState function to change the state value of useState variable) is an asynchronous operation.

Consider the code given below that explains the asynchronous behavior.

As soon as we click the '+' button, this is how the page and the console look like.

state asynchrony

The count variable on the page shows that its value is 1 but on the console, it has been printed that the count value is 0. So why is this happening? The reason is that the state change operations are not synchronous. The console.log() statement in the code will not wait for the setCount() statement and they both get executed asynchronously.

So, initially, the count value was 0, when the button was clicked, the incrementCount function got called, both the setCount() and console.log() statements got called, and since the setCount() function took more time to execute than the console.log() function, the value of count i.e. 0 gets printed on the console and then, the setCount() function incremented the value of the count and it becomes 1. When the count variable changes, the page gets re-rendered and we see 1 printed on the page.

Mutating State in a Functional way

In the section "State Asynchrony", we saw that the "setState" takes some time to execute. Now let us consider a case in which, the '+' button gets clicked 50 times within a very very short period. It seems that the count variable will become "50" after the whole operation. But since the setState function takes some time to execute, there is a possibility that the count variable does not get incremented every time. It is possible that on some clicks, the next click gets executed so fast that there is no time for the previous state to get updated.

Consider the code example given below. To replicate 50 clicks, let us use the setState function inside a loop that runs 50 times on a single click.

After clicking the button, the value for the count variable should have become 50. But the final output shows that the count variable has just incremented by '1' and not '50'.

mutating state in a functional way

To fix this problem, we can use a function inside the setState. The function inside the setState will update the state while taking into consideration the previous state. Hence, in the end, all the state changes will be made while keeping the previous state in consideration, and hence, no update will be missed due to the asynchronous behavior of the state operations.

Given below is the code to implement setState with functions.

On clicking the '+' button a single time, the count variable becomes 50.

mutating state in a functional way

Implementation of useState as a Function in React

Consider a case when we need to call a function as soon as the page loads. This can be done by initializing a useState variable by the same function which is to be called.

Given below is the code to use a function inside useState() in React JS.

Using UseState to Create a React Application

Let us create a React application to input user details in a form. We will use useState in React JS to store the text in the input fields. Given below are the steps to create a react application.

  1. Open a folder inside your code editor and write the npx create-react-app form. This will create a react application with the name 'form'.
  2. After step 1, a folder with the name 'form' will be created. Inside this folder, you will see another folder with the name 'src' which is containing a file with the name 'App.js'. We will be writing our React code inside this file only. Given below is the code to create a form inside this file.

This is what our react page looks like.

react application

Adding input to the page.

react application

When we click on the 'submit form' button, an alert box pops up with all the input values.

react application

Steps to Run Application

To run the application,

  1. Type cd form in the terminal to change the route to the 'form' folder.
  2. Write npm start in the terminal. The react application will run on local host 3000.

Conclusion

  • UseState is one of the react hook that is used to create a variable in a react application that affects the state of the react application.
  • Hooks are the react function that allows us to use or modify the state of a react application.
  • useState in React JS is used to store data in the form of a string, integer, objects, float, etc.
  • Multiple state variables can be defined either individually, or they can be merged into a single state object.
  • In React, the changing/modification of a state (for example using a setState function to change the state value of useState variable) is an asynchronous operation.
  • Since the setState function takes some time to execute, sometimes, some of the changes do not get updated. To solve this, we use a function inside the setState function.