Understanding React State with Practical Examples

0
33

Introduction

React is a commonly used JavaScript library developed by Facebook in 1995. It’s used for creating a single-page application, user interfaces, etc. One of the most useful points is state management. State represents that the data is managed within the component.

In this article, we will discuss the React state with practical examples, such as counters, managing form inputs, etc.

State in React

State is used for managing and tracking the condition of the application using the useState Hook. It is mutable and used for sending data within the component. If you are changing the state, React automatically performs the re-rendering of the component to change the data in the UI.

Syntax:

const [data, setData] = useState(currentState);

Example

Code:

import React, { useState } from "react";

function ToggleText() {

  const [show, setShow] = useState(true);

  return (

    <div>

      <h2>Toggle Text Example</h2>

      {show && <p>Hello! I am visible </p>}

      <button onClick={() => setShow(!show)}>

        {show ? "Hide" : "Show"} Text

      </button>

    </div>

  );

}

export default ToggleText;

Output:

sngine_d7339e6c59ac262a28ef8169e080a829.png

How State Works in React?

React uses the unidirectional data flow, which means that when state changes, React automatically changes the virtual DOM. Here are some of the points that are shown below in detail:

1) Initializing state Object:

Initializing a state Object in React is helpful for making interactive and dynamic components. With the use of a constructor, you can easily initialize a state object in the class component.

Example

Code:

import React from 'react';

class Welcome extends React.Component {

  constructor(props) {

    super(props);

    // Initializing state

    this.state = {

      message: 'Hello, React!'

    };

  }

  render() {

    return (

      <div>

        <h1>{this.state.message}</h1>

      </div>

    );

  }

}

export default Welcome;

2) Modify the state in React:

React state is immutable, which means you cannot directly update the state in React. You can update through the class components this.setState() method but in functional components by useState() method.

Example

Code:

import React, { useState } from 'react';

function Counter() {

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

  return (

    <div>

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

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

    </div>

  );

}

export default Counter;

Manage the state in functional Components:

In modern ways, we use the useState Hook to manage the state in functional components. It contains two values, like the initial state, and updates the state function.

Example

Code:

import React, { useState } from "react";

function UserInfo() {

  const [name, setName] = useState("Tpoint");

  const [age, setAge] = useState(12);

 

  return (

    <div>

      <h2>Name: {name}</h2>

      <h2>Age: {age}</h2>

      <button onClick={() => setName("Tech")}>Change Name</button>

      <button onClick={() => setAge(age + 1)}>Increase Age</button>

    </div>

  );

}

export default UserInfo;

Output:

sngine_a1db3ab0c310e7585b2358c5d4276e42.png

Manage the state in Class Components:

With the use of this component, you can update the state during the component lifecycle. It uses this.setState() method to modify the state values.

Example

Code:

import React from "react";

class LoginInfo extends React.Component {

  constructor(props) {

    super(props);

    this.state = { isLoggedIn: false };

  }

 

  toggleLogin = () => {

    this.setState({ isLoggedIn: !this.state.isLoggedIn });

  };

 

  render() {

    return (

      <div>

        <h2>{this.state.isLoggedIn ? "Welcome Back! " : "Please Log In"}</h2>

        <button onClick={this.toggleLogin}>

          {this.state.isLoggedIn ? "Logout" : "Login"}

        </button>

      </div>

    );

  }

}

export default LoginInfo;

Output:

sngine_393863650f499ffd149ac1c6f71bb505.png

Practical Examples of React state

Some of the examples shown below using the React state:

1) Form Input handling: Using the form input handling to manage the many input values, such as signup forms, login forms, or search bars, etc.

Example

Code:

import React, { useState } from 'react';

function ShowName() {

  const [name, setName] = useState('');

  const [submittedName, setSubmittedName] = useState('');

  const handleSubmit = (e) => {

    e.preventDefault();

    setSubmittedName(name);

  };

  return (

    <div>

      <form onSubmit={handleSubmit}>

        <input

          type="text"

          value={name}

          onChange={(e) => setName(e.target.value)}

          placeholder="Enter your name"

        />

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

      </form>

      {submittedName && <h2>Hello, {submittedName}!</h2>}

    </div>

  );

}

export default ShowName;

Output:

sngine_8c47261fe8d2c6e5f811e4ccd29b3fd2.png

2) Conditional Re-rendering with state: Using conditional rendering to show only those details when a certain condition is true.

Example

Code:

import React, { useState } from 'react';

function SignupForm() {

  const [username, setUsername] = useState('');

  const [submitted, setSubmitted] = useState(false);

 

  const handleSubmit = (e) => {

    e.preventDefault();

    if (username.trim() !== '') {

      setSubmitted(true);

    }

  };

  return (

    <div style={{ textAlign: 'center', marginTop: '20px' }}>

      {!submitted ? (

        <form onSubmit={handleSubmit}>

          <input

            type="text"

            value={username}

            onChange={(e) => setUsername(e.target.value)}

            placeholder="Enter your username"

          />

          <button type="submit">Sign Up</button>

        </form>

      ) : (

        <h2> Welcome, {username}! Your signup is successful.</h2>

      )}

    </div>

  );

}

export default SignupForm;

Output:

sngine_3490b828b07630bcec1647b1a02c6822.png

3) Multiple State Variables: It is useful when it contains multiple input fields, such as user details, cart items, etc.

Example

Code:

import React, { useState } from 'react';

function StudentForm() {

  const [student, setStudent] = useState({

    name: '',

    rollNo: '',

    course: ''

  });

  const [submitted, setSubmitted] = useState(false);

  const handleChange = (e) => {

    const { name, value } = e.target;

    setStudent({

      ...student,

      [name]: value

Rechercher
Catégories
Lire la suite
Health
Breaking Stigmas: Why Adults Need Play Therapy Just as Much as Kids
When people hear the term play therapy, they often associate it with children....
Par Core Wellness 2025-09-08 05:52:33 0 521
Autre
Haldwani to Kainchi Dham Taxi Fare
Book Haldwani to Kainchi Dham cab online at best price. CabBazar provides car rental services for...
Par Cab Bazar 2025-09-22 12:05:29 0 187
Shopping
Choosing the Right Stainless Steel Hot Pot Puff Insulated Manufacturer: A Buyer’s Guide
When it comes to high-quality kitchenware, insulated hot pots are a must-have in every household...
Par Camro Steel 2025-09-23 09:36:51 0 126
Autre
Electrical Wiring Interconnect System (EWIS) Market Demand, Innovations, and Outlook
"Global Executive Summary Electrical Wiring Interconnect System (EWIS) Market: Size, Share,...
Par Danny Patil 2025-08-19 11:10:22 0 816
Jeux
MMOEXP New World:New World Guide: Quick and Easy Ways to Get Named Weapons like Frostbite & Motherwell Wisher's Coin
In New World, world drop named weapons are some of the most sought-after items in the game. These...
Par Damnmy Damnmy 2025-09-24 02:42:59 0 157