Month End Sale: Get Extra 10% OFF on Job-oriented Training! Offer Ending in
D
H
M
S
Get Now
Understanding useState in React

Understanding useState in React

27 May 2024
Beginner
183 Views
11 min read

React useState Hook

React is counted among the most commonly used libraries in the domain of front-end development. It is mainly used for creating user interfaces. React has a component-based structure that makes the code easy to reuse and maintain. At the core of React’s components lies the idea of state, representing the data that can change with time and it affects how components are rendered.

In the past, when developers wanted to keep track of state in their React applications, they had to create class components and use the this.state method. But now with the latest version, we have React Hooks which provide a more sophisticated yet concise means of managing the state within functional components. Out of these hooks, useState is seen as the most important one. In this React Tutorial, we will try to explore React useState and React useState syntax with examples. To learn more about various aspects of React with ReactJS Certification Training.

Read More: React Hooks Interview Questions & Answers

What is useState in React?

useState is one of the Hooks in React which is used to manage the state within the functional components. It is a way through which we can declare state variables and update them within functional components, without the need for class-based syntax.

Import useState in React

The useState Hook is imported from the 'react' library, after which it can be used within the functional components.
import React, { useState } from 'react';
The useState function is then used to initialize state variables and manage the state within the component.

Syntax of React useState

The basic syntax of useStae looks like this:
const [state, setState] = useState(initialState);
Here,
  • state- It is the current state value.
  • setState- It is the function used for updating the state.
  • useState- It takes the initial value of the state variable as an argument.

Example of React useState:

Let us try to understand the structure and usage of useState in React through this simple example below.
import React, { useState } from 'react';

function Counter() {
  const [count, setCount] = useState(0);

  return (
    <div>
      <p>Count: {count}</p>
      <button onClick={() => setCount(count + 1)}>Increment</button>
    </div>
  );
}

export default Counter;
Here, useState(0) will initialize the count state variable with an initial value of 0. The setCount function will then update the count state whenever the 'Increment' button is clicked.

Update State using useState Hook

State is updated using useState by calling the setter function which was returned by useState. This function can be called with the help of a new value to update the state.

Update useState

setCount(count + 1);
Here, setCount is called with the updated value of count, which is then incremented by 1.
Read More: React Roadmap 2024: Roadmap for Beginners to Learn React

Why use React useState

Using React's useState hook offers several advantages that are as follows:
  • Simplicity- With useState, there is no need to use class components or this.syntax syntax.  State variables can be declared directly within the component function with functional components.
  • Readability- Using useState makes the functional components more concise and easier to understand. State-related logic is encapsulated within the component function, making it clear where state is defined and modified.
  • Ease of Use- The syntax for useState is straightforward. We just need to declare a state variable and a corresponding setter function, both of which are used within the component to read and update state values.
  • Encapsulation- Each call to useState creates a separate instance of state that allows components to manage multiple independent state variables. This helps in the encapsulation and separation of concerns within the component.
  • Compatibility with Functional Components- Since useState is a hook designed specifically for functional components, it aligns well with modern React development practices. 

Updating Objects and Arrays in State using React useState

The method for updating objects and arrays in state using the useState hook in React is a little different as compared to updating primitive values.

Updating Objects

When updating objects in state, you should create a new object that merges the existing state with the updated values.
import React, { useState } from 'react';

function Example() {
  const [user, setUser] = useState({ name: 'John', age: 30 });

  // Update user's age
  const updateUserAge = () => {
    setUser(prevUser => ({
      ...prevUser,
      age: prevUser.age + 1
    }));
  };

  return (
    <div>
      <p>Name: {user.name}</p>
      <p>Age: {user.age}</p>
      <button onClick={updateUserAge}>Increase Age</button>
    </div>
  );
}

export default Example;
In the updateUserAge function, we use the callback form of setState, which provides access to the previous state (prevUser). We then create a new object by spreading the previous user object (prevUser) and updating the age property with the incremented value.

Updating Arrays

Similarly, when updating arrays in state, you should create a new array that includes the updated elements.
import React, { useState } from 'react';

function Example() {
  const \[items, setItems\] = useState(\['apple', 'banana', 'cherry'\]);

  // Add a new item
  const addItem = () => {
    setItems(prevItems => \[...prevItems, 'orange'\]);
  };

  // Remove an item
  const removeItem = (itemToRemove) => {
    setItems(prevItems => prevItems.filter(item => item !== itemToRemove));
  };

  return (
    <div>
      <ul>
        {items.map((item, index) => (
          <li key\={index}>
            {item}
            <button onClick\={() => removeItem(item)}>Remove</button>
          </li>
        ))}
      </ul>
      <button onClick\={addItem}>Add Item</button>
    </div>
  );
}

export default Example;
In the addItem function, we create a new array by spreading the previous items array (prevItems) and adding the new item ('orange'). In the removeItem function, we create a new array that will not show the item that needs to be removed, using the filter method.
Read More:
Summary
Through this article, we learned how we can use React useState Hook to manage the state within functional components with examples. To learn more about React and its various concepts, do consider enrolling in the ReactJS Certification Course, and build your React knowledge from scratch with professional guidance.

FAQs

Q1. What is the React useState hook?

The React useState hook allows us to manage state within the functional components.

Q2. What is a hook in React?

A  hook in React is a function with the help of which functional components can use React features like state and lifecycle methods.

Q3. Why use React hooks?

React hooks are useful as they allow reusing of code and improve readability making the development easier.

Q4. What is useState and useEffect?

useState and useEffect are both used in a component where useState is used for managing a state and useEffect is used for performing side effects.

Take our React skill challenge to evaluate yourself!

In less than 5 minutes, with our skill challenge, you can identify your knowledge gaps and strengths in a given skill.

GET FREE CHALLENGE

Share Article

Live Classes Schedule

Our learn-by-building-project method enables you to build practical/coding experience that sticks. 95% of our learners say they have confidence and remember more when they learn by building real world projects.
Generative AI For Software Developers Jul 27 SAT, SUN
Filling Fast
08:30PM to 10:30PM (IST)
Get Details
Software Architecture and Design Training Jul 28 SAT, SUN
Filling Fast
05:30PM to 07:30PM (IST)
Get Details
.NET Solution Architect Certification Training Jul 28 SAT, SUN
Filling Fast
05:30PM to 07:30PM (IST)
Get Details
Azure Developer Certification Training Jul 28 SAT, SUN
Filling Fast
10:00AM to 12:00PM (IST)
Get Details
Advanced Full-Stack .NET Developer Certification Training Jul 28 SAT, SUN
Filling Fast
07:00AM to 09:00AM (IST)
Get Details
ASP.NET Core Certification Training Jul 28 SAT, SUN
Filling Fast
07:00AM to 09:00AM (IST)
Get Details
Data Structures and Algorithms Training with C# Jul 28 SAT, SUN
Filling Fast
08:30PM to 10:30PM (IST)
Get Details
Microsoft Azure Cloud Architect Aug 11 SAT, SUN
Filling Fast
03:00PM to 05:00PM (IST)
Get Details
Angular Certification Course Aug 11 SAT, SUN
Filling Fast
09:30AM to 11:30AM (IST)
Get Details
ASP.NET Core Project Aug 24 SAT, SUN
Filling Fast
07:00AM to 09:00AM (IST)
Get Details

Can't find convenient schedule? Let us know

About Author
Shailendra Chauhan (Microsoft MVP, Founder & CEO at Scholarhat by DotNetTricks)

Shailendra Chauhan is the Founder and CEO at ScholarHat by DotNetTricks which is a brand when it comes to e-Learning. He provides training and consultation over an array of technologies like Cloud, .NET, Angular, React, Node, Microservices, Containers and Mobile Apps development. He has been awarded Microsoft MVP 8th time in a row (2016-2023). He has changed many lives with his writings and unique training programs. He has a number of most sought-after books to his name which has helped job aspirants in cracking tough interviews with ease.
Accept cookies & close this