Open In App

React useState Hook

The useState hook is a powerful addition to React, introduced in version 16.8. It allows you to manage state within functional components without the need for class-based components. In this useState Hooks article, we’ll learn about useState, its syntax, usage and best practices with examples.

What is useState Hook?

In React, useState is a special function that lets you add state to functional components. It provides a way to declare and manage state variables directly within a function component. It should be noted that one use of useState() can only be used to declare one state variable. It was introduced in version 16.8.

Why Use useState?

Functional components are some of the more commonly used components in ReactJS. Most developers prefer using functional components over class-based components for the simple reason that functional components require less coding (on the developer's part). However, two main features for the class are lost when one goes with a functional component - a dedicated state that persists through render calls as well as the use of lifecycle functions to control how the component looks and behaves at separate stages of its lifecycle.

  1. Simplicity: Functional components are preferred due to their concise code. useState simplifies state management.
  2. Avoiding Class Components: With useState, you can handle state without converting your component into a class.

Importing the useState Hook

To import the useState hook, write the following code at the top level of your component

import { useState } from "react";

Structure of React useState hook

This hook takes some initial state and returns two value. The first value contains the state and the second value is a function that updates the state. The value passed in useState will be treated as the default value.

Syntax:

const [var, setVar] = useState(0);

Internal working of useState hook

React useState Hook Examples

Example 1: Using useState Hook

Program to demonstrate the basic use of useState() hook. 

// Filename - App.js

import React, { useState } from 'react';

function App() {
    const click = useState('GeeksForGeeks');
    return (
        <h1>Welcome to {click}</h1>
    );
}

export default App; 

Output:

React useState hook example output

Explanation:

Updating state using useState Hook

To update states using useState we will use the second value passed in useState hook which updates the first value.

Syntax to Update State in useState hook:

setVar(newState);

Example 1: Updating React useState Hook State

Program to demonstrate the use of a state variable in a functional component and how to update it accordingly. 

// Filename - App.js

import React, { useState } from 'react';

function App() {
    const [click, setClick] = useState(0);
    // using array destructuring here 
    // to assign initial value 0
    // to click and a reference to the function 
    // that updates click to setClick
    return (
        <div>
            <p>You clicked {click} times</p>

            <button onClick={() => setClick(click + 1)}>
                Click me
            </button>
        </div>
    );
}

export default App;

Output:

React useState Hook example Output

Example 2: React useState Hooks Previous Value

Program to demonstrate the use of the last value while updating the value of the 'state' variable. 

// Filename - App.js 

import React, { useState } from 'react';

function App() {
    const [click, setClick] = useState(0);
    return (
        <div>
            <p>You've clicked {click} times!</p>
            <p>The number of times you have clicked
                is {click % 2 == 0 ? 'even!' : 'odd!'}</p>
                
            <button onClick={() => setClick(click => click + 1)}>
                Click me
            </button>
        </div>
    );
}

export default App;

Output:

React useState hook example output

Explanation:

In the above example,

Updating arrays and object using useState hook

Sometimes we only want part of a state object to be updated instead of the whole state to do that we use the spread operator to fetch previous values and then add the new value

Example 1: React useState Hook Arrays

Program to demonstrate the use of arrays as a state variable (using useState()). 

// Filename - App.js

import React, { useState } from 'react';

function App() {
    const [click, setClick] = useState([]);

    const addNumber = () => {
        setClick([
            ...click,
            {
                id: click.length,
                value: Math.random() * 10
            }
        ]);
    };

    return (
        <div>
            <ul>
                {click.map(item => (
                    <li key={item.id}>{item.value}</li>
                ))}
            </ul>
            <button onClick={addNumber}>
                Click me
            </button>
        </div>
    );
}

export default App;

Output:

React useState hook example output

Explanation:

Example 2: React useState Hook Object

Program to demonstrate the use of objects as a state variable (using useState()). 

// Filename - App.js 

import React, { useState } from 'react';

function App() {
    const [data, setData] = useState({
        username: '',
        password: ''
    });
    const [form, setForm] = useState({
        username: '',
        password: ''
    });
    const [submit, submitted] = useState(false);

    const printValues = e => {
        e.preventDefault();
        setForm({
            username: data.username,
            password: data.password
        });
        submitted(true);
    };

    const updateField = e => {
        setData({
            ...data,
            [e.target.name]: e.target.value
        });
    };

    return (
        <div>
            <form onSubmit={printValues}>
                <label>
                    Username:
                    <input
                        value={data.username}
                        name="username"
                        onChange={updateField}
                    />
                </label>
                <br />
                <label>
                    Password:
                    <input
                        value={data.password}
                        name="password"
                        type="password"
                        onChange={updateField}
                    />
                </label>
                <br />
                <button>Submit</button>
            </form>

            <p>{submit ? form.username : null}</p>

            <p>{submit ? form.password : null}</p>
        </div>
    );
}

export default App;

Output:

React useState hook example output

Explanation:

In the above example,

Article Tags :