React hooks useState


React hooks are latest features introduced in functional classes to limit class component uses.

React supports two types of component types.

  • Functional components: these are functions with arguments and return JSX (mix of javascript and html) code and there is no state management before react V0.16.7 version, also called as stateless components.
  • Class components: these are stateful components, contains state, lifecycle methods, these are created by extending React.Component class.

Several hooks are introduced in react latest versions. useState is built in hook introduced in React to update state object in Functional components.

useState in React functional components

useState abbreviated as use state management in functional components.

In functional components, Storing an local state of a component using useState hook.

State can be of any type- array, object,Boolean, number and string etc. useState holds only single type of an data.

First, import useState in component

import React, { useState } from 'react';

Syntax:

const [variable, setFunction] = useState(defaultValue);

variable is new state variable assigned with default value. setFunction is an function to update the state variable.

useState feature

  • It can be used in functional components or stateless components
  • The state of an component can be managed with this
  • It always return initial value and a function to update a
  • Hooks are not used in react classes

Example, Adding state to functional components

Let’s see an example to increment value in React class components with button click

In react class components,

  • State stores as an object that means can store different types of data (Boolean,array)
import React, { Component } from 'react';

class IncrementCounter extends Component {
    constructor(props) {
        super(props);
        this.state = {
            count: 0,
        }
    }
    incrementCounter() {
        this.setState(previous => ({ count: previous.count + 1 }));

    }
    render() {
        const { count } = this.state;
        return (
            <div>
                <p>Incremented to  {count}</p>

                <input type="button" name="countr" value="Increment" onClick={(e) => this.incrementCounter(e)} />
            </div>
        );
    }
}

export default IncrementCounter;

useState in React functional components

The above can be rewritten using useState hook with functional components

import React, { useState } from 'react';

function IncrementCounterHook(props) {
    const [counter, setCounter] = useState(0);

    return (
        <div>
            <div>Incremented to {counter}</div>
            <input type="button" name="countr" value="Increment" onClick={() => setCounter(counter + 1)} />

        </div>
    );
}

export default IncrementCounterHook;

Let’s see few examples to update state object

What is difference between state in functional components and class components

useState hook update array in functional component

This example explains store or update an array in array component. below code, submitting form with input name and added to state array with functional component

  • useState is defined with initial state as []
  • It returns state variable employees of array type and a method setEmployee to update an array.
  • addEmployee is called on button click handler
  • setEmployees copy the existing employees array and add the new value to it.
  • spread operator … is used to add new employee to employees.
  • Finally displays the state array using array map function
import React, { useState } from 'react';

function HookArray(props) {
    const [employees, setEmployees] = useState([]);
    const [name, setName] = useState("");

    const addEmployee = event => {
        event.preventDefault();
        setEmployees([
            ...employees,
            {
                name: name
            }
        ]);
        setName("");
    };

    return (
        <div>
            <>
                <form onSubmit={addEmployee}>

                    <label>Name
                        <input
                            name="name"
                            type="text"
                            value={name}
                            onChange={e => setName(e.target.value)}
                        />
                    </label>
                    <button name="Add" value="Add">Add</button>
                </form>
                <ul>
                    {employees.map(emp => (
                        <li key={emp.empid}>{emp.name}</li>
                    ))}
                </ul>
            </>
        </div>
    );
}

export default HookArray;
THE BEST NEWSLETTER ANYWHERE
Join 6,000 subscribers and get a daily digest of full stack tutorials delivered to your inbox directly.No spam ever. Unsubscribe any time.

Similar Posts
Subscribe
You'll get a notification every time a post gets published here.