Table of contents
1.
Introduction
2.
What is useState() in React Js?
2.1.
Syntax
2.2.
React useState() example
2.3.
Creating the React app
3.
Why Use useState?
4.
When should you use the useState Hook?
4.1.
Before using useState() in React Js:
5.
Reason to choose useState hook
6.
How to use useState hook?
7.
Reading State
8.
Updating State
9.
What are Hooks in React?
10.
What can the State hold?
10.1.
Implementation
11.
Updating Arrays and Object states.
12.
Frequently Asked Questions
12.1.
What is useState in React JS?
12.2.
What is the difference between useEffect and useState?
12.3.
Why is const used in useState?
13.
Conclusion
Last Updated: Nov 17, 2024
Easy

useState() in React Js

Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

React hooks reduce code size and make it easier to read, concise, and understandable. React hook APIs replace class-based components, providing state management and lifecycle methods that are more efficient than class components. This feature enables developers to use functional components for nearly everything, from rendering the UI to handling state and logic. Through hooks, functionality that was once only possible with classes can now be added to functional components, like working with useState, useEffect, and useContext, etc. Let's see how useState works.
 

useState() in React Js

What is useState() in React Js?

React developers can use the useState() hook to update, manage and manipulate states inside functional components without converting them to class components. 
You can add states to function components with this tool. useState() in ReactJS is an internal method called inside function components to create a state associated with each component. While the state of a class is always an object, hooks can have any state. A state is made up of a single value, an object, an array, a boolean, or some other type. It is important to remember that when you use multiple useState hooks, all of them must be executed in order. 

Syntax

import React, { useState } from 'react';
function func() {
 const [stateVariable, setStateVariable] = useState(initialStateValue);
 // ...code
}

React useState() example

Example 1:

import React, { useState } from 'react';
function func() {
 const [clicks, setClicks] = useState(0);
 return (
   <div>
     <p>You have clicked {clicks} times</p>
     <button onClick={() => setClicks(clicks + 1)}>
       Click here
     </button>
   </div>
 );
}


Example 2(with class):
 

class hook extends React.Component {
 constructor(prop) {
   super(prop);
   this.state = {
     count: 0
   };
 }
 render() {
   return (
     <div>
       <p>You have clicked {this.state.count} times</p>
       <button onClick={() => this.setState({ count: this.state.count + 1 })}>
         Click here
       </button>
     </div>
   );
 }
}

Creating the React app

Step1: Install Node.js: If you don't have Node.js installed, you'll need to install it on your machine. You can download it from the official website: https://nodejs.org/.
 

Step2: Install Create React App: Open a terminal or command prompt and run the following command:
 

npm install -g create-react-app


This will install Create React App globally on your machine.

 

Step3: Create a new React app: In the command prompt, point to that directory where you want to create your new React app and run the following command:
 

npx create-react-app my-app


Replace "my-app" with the name of your desired app.
 

Step4: Start the development server: Navigate into the newly created app directory and run the following command:
 

cd my-app
 npm start


This will start the development server and open your app in a browser at http://localhost:3000.
That's it! You now have a new React app up and running. You can start making changes to the code in the "src" directory and see the changes reflected in the browser.

Why Use useState?

useState is a tool used in React, to allow pieces of a website (components) to remember information and change over time. It's like giving them a memory. This is important because it makes your website more dynamic and interactive. For example, a component could remember if a user has clicked a button or not, and change its color based on that.

When should you use the useState Hook?

It can be used to provide some conditional rendering, in which the DOM needs to be updated when the UI changes. The solution is especially helpful at the local component state level; additional state management solutions might be necessary for larger projects.
The code below demonstrates how to increase/decrease the count by clicking the buttons in the picture. Since it is just HTML, we can't increase or decrease the count at the moment. To add functionality to the buttons, we have to use useState() in React Js.

Before using useState() in React Js:

import React from "react";
function App() {
  return (
    <>
      <button>-</button>
      <span> 0 </span>
      <button>+</button>
    </>
  );
}
export default App;


Output:

output

Reason to choose useState hook

In React.js, the useState hook is commonly used for managing state within functional components. Here are several reasons to choose the useState hook:

  • Functional Components: The useState hook enables state management in functional components, allowing developers to write stateful logic without the need for class components.
  • Declarative State Updates: useState provides a clean and declarative way to handle state updates. The setter function returned by useState ensures that updates do not mutate the existing state.
  • Simple Syntax: The useState syntax is concise and easy to understand. It takes an initial state as an argument and returns an array containing the current state and a function to update that state.
  • Multiple State Variables: You can use useState multiple times within a component to manage different pieces of state independently. This allows for more granular control over the state of different components.
  • Functional Updates: The setter function returned by useState allows for functional updates. This is useful when the new state depends on the previous state, helping avoid issues related to the asynchronous nature of state updates.
  • Automatic Merging of State: When using an object as state, useState automatically merges the existing state with the new state provided. This is especially handy for managing complex state structures.
  • Performance Optimizations: React is optimized to perform state updates efficiently using the useState hook. It employs techniques like batching updates to minimize unnecessary renders.

How to use useState hook?

The useState should be imported from the react Hook. The hooks can only be used within function components; they cannot be used in class components. In this picture, you can see a functional app component.
 

import React, { useState }from "react";


This can be accomplished by calling the usestate() function with a user-defined parameter. The useState() in React Js returns two values. We will have two values here: 

  • The first one is your state called "count," which is the current state at every single iteration of our render and,
     
  • The second is the "setCount" function that will allow us to change this state.
import React, { useState }from "react";
function App() {
  const [count, setCount] = useState(0)
   // "0" means the counter will start at 0 and "ar" will store an array of values.
  return (
    <>
      <button>-</button>
      <span> {count} </span>
      <button>+</button>
    </>
  );
}
export default App;

 

We will create an onClick function for both buttons to show their functionality in creating the setCount value.

import React, { useState }from "react";
function App() {
  // "0" means the counter will start at 0 and "ar" will store an array of values.
  const [count, setCount] = useState(0) 
  //function to decrement the current value by 1 
  function decrementCount() {
    setCount(prevCount => prevCount - 1)
  }
  //function to increament the current value by 1 
  function increamentCount() {
    setCount(prevCount => prevCount + 1)
  }
  return (
    <>
      <button onClick={decrementCount}>-</button>
      <span> {count} </span>
      <button onClick={increamentCount}>+</button>
    </>
  );
}
export default App;

 

Output:

The final thing you can see is that by clicking each button, the count will increase or decrease by its previous value.

output
output

Reading State

You can read the state by writing the state variable in { State_name } mentioned in the Function App() you have created, here, we have named it as count.

import React, { useState }from "react";
function App() {
  const [count, setCount] = useState(0)
  return (
    <>
      <button> Read demo</button>
      <span> {count} </span> 
    </>
  );
}
export default App;

 

Output:

output

Updating State

The state should never be directly updated. ex: count = "6" is not allowed. You need to pass an onClick().
 

import React, { useState }from "react";
function App() {
  const [count, setCount] = useState(0)
  return (
    <>
      <button type="button"onClick={()=>setCount("6")}> Update demo</button>
      <span> {count} </span> 
    </>
  );
}
export default App;


Output:

output


On Clicking on the update button the value will be changed to 6.
 

output

What are Hooks in React?

Hooks are the functions that help us use state, and other React Js features without defining a class. Hooks allow us to write our logic in functional components without needing class components.

Let’s discuss some standard Hooks in React Js.

  • useState (): This Hook allows us to manipulate states inside the functional components and returns the current state value and the updater function that updates the state value.
     
  • useEffect (): These are the Hooks used to perform side effects in our applications. Side effects are the things happening as a consequence of something else. In most of the cases, side effects are the results of changing states.  
     
  • useContext(): Context is a way to manage state globally, and to use the context in a child component, we need to access it using the useContext Hook. 
     
  • useCallback (): It allows us to memoize a function and prevent it from being recreated on each render. These Hooks only run when one of their dependencies is updated.
     
  • Custom Hooks: It is a Javascript function that begins with the word “use” and can invoke other Hooks. Custom Hooks allow us to reuse stateful functionality across components without adding extra components.

What can the State hold?

The State created using ‘useState’ can hold any type of data, including primitive types such as integers, boolean values, strings, objects, and arrays. 

Let’s take an example to see how ‘useState’ manages different types of states.

Implementation

import React, { useState } from 'react';

const Myfunction = () => {

 /* State variables */

 const [intValue, setintValue] = useState(20); // Number
 const [stringValue, setStringValue] = useState('Mike'); // String
 const [booleanValue, setBooleanValue] = useState(true); // Boolean

 return (
   <div>
     <p>Integer Value: {intValue}</p>
     <p>String Value: {stringValue}</p>
     <p>Boolean Value: {booleanValue ? 'Yes' : 'No'}</p>
   </div>
 );
};

export default Myfunction;

 

Output

output


In the example above, we’ve created different state variables using ‘useState’ to hold various data types. The ‘intValue’ state is a number, ‘stringValue’ is a string, and ‘booleanValue’ is a boolean state. We are initializing our state variables by calling the ‘useState’ function. 

Updating Arrays and Object states.

A copy of the value must be created before we can modify it in our React state if we want to use arrays or objects.

import React, { useState }from "react";
function App() {
  const [count, setCount] = useState({
  year: 2022,
  month: 5,
  day: "Saturday"
  });
    const updateCount = () => {
      setCount(previousState => {
        return { ...previousState, day: "Sunday", month: 6 }
      });
    }
  return (
    <>
      <button onClick={updateCount}> Update object</button>
      <span> Today's day is: {count.year}/{count.month}/{count.day} </span> 
    </>
  );
}
export default App;


Output:

output


On Clicking the button, the output will be changed to:
 

output

Frequently Asked Questions

What is useState in React JS?

useState is a React Hook that allows functional components to manage and update state variables, enabling dynamic rendering based on state changes.

What is the difference between useEffect and useState?

useState manages component state, while useEffect handles side effects like data fetching, subscriptions, or updating the DOM after render.

Why is const used in useState?

const ensures the state variable and its updater function remain immutable, preventing accidental reassignment while still allowing state updates via the updater.

Conclusion

This blog shows that useState() in React JS is used to add functionality to functional components and a brief description of when and how we can implement the useState() in React Js.

Recommended Readings:

We hope you have found this blog helpful in learning how to use useState() in React Js and if you want more information, check out our articles on the Code360Refer to our guided paths on Code360 to upskill yourself in Data Structures and AlgorithmsCompetitive ProgrammingJavaScriptSystem Design, and many more! If you want to test your competency in coding, you may check out the mock test series and participate in the contests hosted on Code360! You can also consider our React Js Course to give your career an edge over others.

Live masterclass