Open In App

React useState Hook

Improve
Improve
Like Article
Like
Save
Share
Report

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

  • useState() creates a new cell in the functional component’s memory object.
  • New state values are stored in this cell during renders.
  • The stack pointer points to the latest cell after each render.
  • Deliberate user refresh triggers stack dump and fresh allocation.
  • The memory cell preserves state between renders, ensuring persistence.

React useState Hook Examples

Example 1: Using useState Hook

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

javascript
// 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:

  • useState() returns an array with initial state value and a function to update it.
  • Array destructuring simplifies simultaneous assignment.
  • Separate assignment is possible using the array indecies.

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. 

javascript
// 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. 

javascript
// 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,

  • Arrow function within setClick() receives the previous click value, allowing data manipulations based on the state.
  • Useful for cases where the new state depends on the existing state value.

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()). 

javascript
// 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:

  • 'useState()' behaves differently from ‘setState()' in class components, particularly with arrays.
  • 'setClick()' in ‘useState()' overwrites array values, not merging them.
  • Use spread operator in addNumber() to append existing values to the array.
  • Objects are efficient for handling diverse data types, streamlining work and reducing ‘useState()' declarations.
  • Objects in state management enhance code organization, scalability, and maintainability.
  • Objects offer a holistic view of the component’s state, facilitating clearer representation and extraction of specific data attributes.

Example 2: React useState Hook Object

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

javascript
// 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,

  • ‘data’ variable temporarily stores entered username and password values using the spread operator to update existing values.
  • Stores values submitted through the form, displayed below the form after submission.
  • Copies existing field values, updating them based on user input in the component.
  • ‘setForm()’ updates ‘form’ state variable without using the spread operator, neglecting the need for previous values.
  • Omitting spread operator in ‘setForm()’ eases management since past username and password values are not relevant.


Last Updated : 19 Mar, 2024
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads