1. Home
ReactJS

ReactJS Tutorial: A Comprehensive Guide

Master ReactJS with our in-depth tutorials. From beginner to advanced topics, explore essential concepts and build dynamic web applications effortlessly.

  • 10
  • 3
right-top-arrow
4

Getting Started with useState in React: A Beginner's Guide

Updated on 03/09/2024432 Views

Introduction

Let us understand the concept of useState with a simple example. Imagine planning a dinner party for friends and writing down the items you need to purchase. Consider useState in React as your mental note-taking process in this scenario. Initially, your list is empty, just like the initial state in React components. As you remember the items you need, you add them to your list similar to updating the state with useState. If you realize you already have an item or don't need it, remove it from your list, mirroring state updates in React. Additionally, if you have purchased an item, you mentally check it off your list, similar to how useState can manage boolean flags to track whether an item is purchased. With each addition, removal, or modification, your shopping list dynamically updates, just as React components update their state, ensuring your dinner party planning process—and your React application—remain organized and responsive to your needs.

Overview

React, a JavaScript library for building user interfaces, introduced Hooks in version 16.8. useState is one of the most fundamental Hooks provided by React. It enables functional components to manage state without the need for class components. In this tutorial, we will explore the effective use of useState in React applications.

What is useState?

useState is a hook that allows you to add state to functional components. It takes a single argument that is the initial sate and returns an array containing the current state value and a function to update it.

Why Use useState?

Before Hooks, state management in React was primarily achieved using class components. However, class components can be complex and more challenging to understand, especially for new developers. Hooks provide a more straightforward and functional approach to managing state, making components more concise and easier to maintain.

Basic Syntax of useState in React

The useState Hook is used by importing it from the 'react' package:

import React, { useState } from 'react';

The useState Hook returns an array with two elements: the current state value and a function to update it. The syntax for using useState is as follows:

const [state, setState] = useState(initialState);

  • state: Represents the current state value.
  • setState: This is a function used to update the state.
  • initialState: Represents the initial value of the state.

Declaring state in React

There are two primary ways to declare state in React:

Class Components:

In class components, state is declared within the component's constructor using ‘this.state’. Here's an example:

import React, { Component } from 'react';

class MyComponent extends Component {

  constructor(props) {

    super(props);

    this.state = {

      count: 0,

      message: 'Hello, World!'

    };

  }

  render() {

    return (

      <div>

        <p>Count: {this.state.count}</p>

        <p>Message: {this.state.message}</p>

      </div>

    );

  }

}

export default MyComponent;

In this example, ‘this.state’ is used to declare an initial state object with count and message properties.

Functional Components with Hooks:

In functional components, useState in React class component can be declared using the useState Hook from React. Here is how you can declare state in a functional component:

import React, { useState } from 'react';

const MyComponent = () => {

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

  const [message, setMessage] = useState('Hello, World!');

  return (

    <div>

      <p>Count: {count}</p>

      <p>Message: {message}</p>

    </div>

  );

}

export default MyComponent;

In this example, useState is used to declare state variables count and message, along with their respective setter functions setCount and setMessage.

In both cases, the declared state variables (‘this.state’ in class components or variables returned by useState in functional components) can be accessed and modified within the component's render function, allowing the UI to update in response to changes in state.

Using useState in a Functional Component

Let us understand functional component with a simple useState in react example:

import React, { useState } from 'react';

const Counter = () => {

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

  return (

    <div>

      <p>Count: {count}</p>

      <button onClick={() => setCount(count + 1)}>Increment</button>

    </div>

  );

};

export default Counter;

In this example:

  • We initialize a state variable count using useState(0) with an initial value of 0.
  • We render the current value of count within a paragraph element.
  • We render a button that, when clicked, calls setCount to update the count state by incrementing it by 1.

Handling Complex State

useState is not limited to managing simple primitive values like strings or numbers. It can also handle complex state, such as objects or arrays. Let us see an example:

import React, { useState } from 'react';

const Form = () => {

  const [formData, setFormData] = useState({

    username: '',

    email: '',

    password: ''

  });

  const handleInputChange = (e) => {

    const { name, value } = e.target;

    setFormData({

      ...formData,

      [name]: value

    });

  };

  const handleSubmit = (e) => {

    e.preventDefault();

    console.log(formData); // Log form data

  };

  return (

    <form onSubmit={handleSubmit}>

      <input

        type="text"

        name="username"

        placeholder="Username"

        value={formData.username}

        onChange={handleInputChange}

      />

      <input

        type="email"

        name="email"

        placeholder="Email"

        value={formData.email}

        onChange={handleInputChange}

      />

      <input

        type="password"

        name="password"

        placeholder="Password"

        value={formData.password}

        onChange={handleInputChange}

      />

      <button type="submit">Submit</button>

    </form>

  );

};

export default Form;

In this example:

  • We initialize a state variable formData using useState, which is an object with keys username, email, and password.
  • We use separate input elements for each field and bind their values to the corresponding keys in the formData object.
  • We define an onChange event handler handleInputChange that updates the formData state whenever the user types in any field.
  • We define a handleSubmit function that logs the form data when submitted.

Updating State Based on Previous State

Sometimes, you may need to update the state based on its previous value. In such cases, you can pass a function to setState instead of an immediate value. This function receives the previous state as an argument. Let us see an example:

import React, { useState } from 'react';

const Counter = () => {

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

  const increment = () => {

    setCount(prevCount => prevCount + 1);

  };

  const decrement = () => {

    setCount(prevCount => prevCount - 1);

  };

  return (

    <div>

      <p>Count: {count}</p>

      <button onClick={increment}>Increment</button>

      <button onClick={decrement}>Decrement</button>

    </div>

  );

};

export default Counter;

In this example, we define increment and decrement functions that update the count state based on its previous value.

useState in React with Object

Here is a react usestate object example

Suppose, we want to build a simple form where users can enter their name and age. We will use useState to manage the state of the form data, which consists of an object with name and age properties.

import React, { useState } from 'react';

const Form = () => {

  // Using useState to manage the form data state

  const [formData, setFormData] = useState({ name: '', age: '' });

  // Function to handle changes in form inputs

  const handleChange = (e) => {

    // Extracting the name and value from the input field

    const { name, value } = e.target;

    // Updating the formData state with the new value

    setFormData({ ...formData, [name]: value });

  };

  // Function to handle form submission

  const handleSubmit = (e) => {

    e.preventDefault();

    // Do something with the form data, for example, logging it

    console.log(formData);

  };

  return (

    <form onSubmit={handleSubmit}>

      <div>

        <label htmlFor="name">Name:</label>

        <input

          type="text"

          id="name"

          name="name"

          value={formData.name}

          onChange={handleChange}

        />

      </div>

      <div>

        <label htmlFor="age">Age:</label>

        <input

          type="text"

          id="age"

          name="age"

          value={formData.age}

          onChange={handleChange}

        />

      </div>

      <button type="submit">Submit</button>

    </form>

  );

};

export default Form;

In this example:

  • We import useState from React.
  • Inside the Form component, we call useState({ name: '', age: '' }) to initialize a state variable called formData with an initial value of an empty object.
  • We define a handleChange function to handle changes in the form inputs. This function updates the formData state with the new values whenever the user types in the input fields.
  • The name and age input fields are bound to the respective properties of the formData object, using the value attribute.
  • When the form is submitted, the handleSubmit function is called, which prevents the default form submission behavior and logs the form data (the formData object) to the console.

Best Practices for Using useState

Here are some of the best practices to follow when using useState in React typescript to ensure clean and maintainable code:

Initialize state with the correct type: Make sure to provide the correct initial value when using useState. For example, if the state is a string, provide an empty string as the initial value.

Use state carefully: Avoid using state for everything. Do not use state if a value does not need to be managed within a component. Consider passing it down as props instead.

Update state immutably: When updating state in React that is an object or an array, always create a new copy of the state rather than mutating the original state directly. This ensures that React can properly detect changes and trigger re-renders.

Separate state concerns: If a component has multiple state variables, consider breaking them into separate useState calls. This makes the code easier to read and maintain.

Consider using useReducer for complex state logic: If your component's state logic becomes too complex, consider using the useReducer hook, which is suitable for managing state in such scenarios.

Wrapping Up!

In this tutorial, we have explored the basics of using the useState in React for state management within functional components. We have covered its syntax, basic usage, handling complex state, and updating state based on the previous state. With useState, you can effectively manage state in your React applications, making them more concise and easier to maintain. 

Frequently Asked Questions (FAQs)

  1. What is useState () in React?

    useState() in React is a hook that allows functional components to manage state.
  1. What is useState in React app?

    useState in a React Native app is a hook to declare state variables in functional components.
  1. When should I use useState in React?

    useState React should be used when you need to manage state within functional components, enabling them to hold and update data dynamically.
  1. What is the benefit of useState in React?

    The benefit of useState in React is that it enables functional components to hold and update their state, simplifying state management and making components more reusable.
  1. What are Hooks in React?

    Hooks in React enable functional components to use state and other React features without writing a class.
  1. Why useState is called twice in React?

    useState is sometimes called twice in React because the first call initializes the state and the second call retrieves the current state value and a function to update it.
  1. Why useState is used?

    useState is used in React to add state management capabilities to functional components.
  1. How does useState work?

    useState returns a state variable and a function to update it. The initial state value is passed as an argument to useState.
  1. What is the difference between useState and state in React?

    The difference between useState and state in React is that useState is a hook used in functional components to manage state, while state is a property used in class components for the same purpose.
Kechit Goyal

Kechit Goyal

Team Player and a Leader with a demonstrated history of working in startups. Strong engineering professional with a Bachelor of Technology (BTech…Read More

Talk to Career Expert
form image
+91
*
By clicking, I accept theT&Cand
Privacy Policy
image
Join 10M+ Learners & Transform Your Career
Learn on a personalised AI-powered platform that offers best-in-class content, live sessions & mentorship from leading industry experts.
right-top-arrowleft-top-arrow

upGrad Learner Support

Talk to our experts. We’re available 24/7.

text

Indian Nationals

1800 210 2020

text

Foreign Nationals

+918045604032

Disclaimer

upGrad does not grant credit; credits are granted, accepted or transferred at the sole discretion of the relevant educational institution offering the diploma or degree. We advise you to enquire further regarding the suitability of this program for your academic, professional requirements and job prospects before enr...