Year End Sale: Get Upto 40% OFF on Live Training! Offer Ending in
D
H
M
S
Get Now
Understanding useState in React

Understanding useState in React

27 May 2024
Beginner
575 Views
11 min read
Learn with an interactive course and practical hands-on labs

ReactJS Course

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

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

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

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

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
About Author
Shailendra Chauhan (Microsoft MVP, Founder & CEO at ScholarHat)

Shailendra Chauhan, Founder and CEO of ScholarHat by DotNetTricks, is a renowned expert in System Design, Software Architecture, Azure Cloud, .NET, Angular, React, Node.js, Microservices, DevOps, and Cross-Platform Mobile App Development. His skill set extends into emerging fields like Data Science, Python, Azure AI/ML, and Generative AI, making him a well-rounded expert who bridges traditional development frameworks with cutting-edge advancements. Recognized as a Microsoft Most Valuable Professional (MVP) for an impressive 9 consecutive years (2016–2024), he has consistently demonstrated excellence in delivering impactful solutions and inspiring learners.

Shailendra’s unique, hands-on training programs and bestselling books have empowered thousands of professionals to excel in their careers and crack tough interviews. A visionary leader, he continues to revolutionize technology education with his innovative approach.
Accept cookies & close this