React useState Hook

In this tutorial, we will learn how to use the useState Hook in Functional components in a React App.

Hooks are a new addition in React 16.8. They allow you to use state, life cycle methods and other React features without writing a class component. If we are using hooks we can have only a functional component in the entire application.

React useState Hook Overview

The useState is a Hook (function) that allows you to have state variables in functional components. To use hooks, first, we should import the useState hooks from react. The useState is a function that takes one argument and returns a current state and a function that lets you update it.

The syntax for using the useState hook is as follows:

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

It takes an initial value as an argument and returns an array with two elements: the current state value and a function to update that value.

Example 1: Simple Example using useState Hook

This example demonstrates the usage of the useState hook to manage the state in a functional component. It initializes state variables, updates them using the provided setter functions, and renders the component based on the current state values. 

In the below example, we are initializing state variables using useState: Inside the Employee component, three state variables (firstName, lastName, and email) are initialized using the useState hook.

import { useState } from "react";

function Employee() {

    const [firstName, setFirstName] = useState('Ramesh')
    const [lastName, setLastName] = useState('Fadatare')
    const [email, setEmail] = useState('[email protected]')

    function updateEmployee(){
        setFirstName('Ram');
        setLastName('Jadhv')
        setEmail('[email protected]')
    }

    return (
        <div>
        <h1> Employee Details</h1> <hr />
        <p>{firstName}</p>
        <p>{lastName}</p>
        <p>{email}</p>

        <button onClick={updateEmployee}>Update Employee</button>
    </div>
    )
}

export default Employee

The useState hook returns an array with two elements: the current state value and a function to update that value. The initial state values are provided as arguments to useState. Here, the initial values for firstName, lastName, and email are set.

    const [firstName, setFirstName] = useState('Ramesh')
    const [lastName, setLastName] = useState('Fadatare')
    const [email, setEmail] = useState('[email protected]')

The updateEmployee function is defined within the Employee component. It is triggered when the "Update Employee" button is clicked. Inside this function, the setFirstName, setLastName, and setEmail functions are used to update the respective state variables.

    function updateEmployee(){
        setFirstName('Ram');
        setLastName('Jadhv')
        setEmail('[email protected]')
    }

Inside the return statement, the component renders the employee details (first name, last name, and email) using the state variables:

        <h1> Employee Details</h1> <hr />
        <p>{firstName}</p>
        <p>{lastName}</p>
        <p>{email}</p>

Example 2: Define State Object using useState Hook

In the below example, instead of defining the state variable of type string, we are defining state object:
import { useState } from "react";

function Employee() {

    const [employee, setEmployee] = useState({
        firstName: 'Ramesh',
        lastName: 'Fadatare',
        email: '[email protected]'
    });

    function updateEmployee(){
        setEmployee({
            firstName: "ram",
            lastName: "jadhav",
            email: '[email protected]'
        })
    }

    return (
        <div>
        <h1> Employee Details</h1> <hr />
        <p>{employee.firstName}</p>
        <p>{employee.lastName}</p>
        <p>{employee.email}</p>

        <button onClick={updateEmployee}>Update Employee</button>
    </div>
    )
}

export default Employee

In this above example, we use defining and initializing state object using the useState hook in a functional component:

  const [employee, setEmployee] = useState({

        firstName: 'Ramesh',
        lastName: 'Fadatare',
        email: '[email protected]'
    });

Example 3: Define State Array using useState Hook

In the below example, we are defining an array as a state variable in a functional component:
const Employee = () => {

    const dummyData = [
        {"id":1,"firstName":"Ramesh","lastName":"Fadatare","email":"[email protected]"},
        {"id":2,"firstName":"Ram","lastName":"Jadhav","email":"[email protected]"},
        {"id":3,"firstName":"Tony","lastName":"Stark","email":"[email protected]"}
    ];

    const [employees, setEmployees] = useState(dummyData)

    return (
        <div className = "container">
            <h2 className = "text-center"> List Employees </h2>
            <table className="table table-bordered table-striped">
                <thead>
                    <th> Employee Id </th>
                    <th> Employee First Name </th>
                    <th> Employee Last Name </th>
                    <th> Employee Email Id </th>
                </thead>
                <tbody>
                    {
                        employees.map(
                            employee =>
                            <tr key = {employee.id}> 
                                <td> {employee.id} </td>
                                <td> {employee.firstName} </td>
                                <td>{employee.lastName}</td>
                                <td>{employee.email}</td>
                            </tr>
                        )
                    }
                </tbody>
            </table>
        </div>
    )
}

export default Employee
Note that we are passing the initial value to useState hook as an array:
    const dummyData = [
        {"id":1,"firstName":"Ramesh","lastName":"Fadatare","email":"[email protected]"},
        {"id":2,"firstName":"Ram","lastName":"Jadhav","email":"[email protected]"},
        {"id":3,"firstName":"Tony","lastName":"Stark","email":"[email protected]"}
    ];

    const [employees, setEmployees] = useState(dummyData)

Related Tutorials

Comments