What Is The useState In React: A Complete Guide?

March 01, 2023
What is the useState in React A Complete Guide



In React, a component is either a class or a function. The definition helps coders keep development simple. Before the launch of React v16.8, they could only use class components to manage data, while functions rendered user interfaces.

However, the introduction of hooks like React useState changed the game. With these, coders can now manage data using states and deploy lifecycle methods in functional components.

The feature has tilted the balance from classes to functions in React, as the latter have a relatively cleaner syntax.

react jobs

In this article, we’ll cover react useState() hook, what it does, why use it, and how it works. Further, we will also share two rules and coded examples of data types it could hold.

What Does React Hook Do?

In plain words, react hooks convert stateless functional components into stateful components and let you work in react without delving into classes. They enable coders to define states in functions for data management and work with lifecycle methods.

What is React useState() Hook?

A state is a mutable, editable storage for data and properties in React. They work directly in classes, while useState() helps manage them in functions. Using this, a developer can add states for data management to functional components.

However, it is essential to remember any state formed using this hook is workable only in the root component, much like variables being only workable within the function’s scope.

Moreover, the useState() hook lets you work with a single data variable, unlike class components, where a single state can hold multiple data variables.

How Does React useState() Hook Work?

To better understand the react useState() hook, it is a must to code an example. Below is the syntax to store and update data value in class components.

class App extends component {

    constructor(props) {

        super(props);

        this.state = { count: 0 };s

    }


    incrementCount = () => {

        this.setState({ count: this.state.count + 1 });

    };

    render() {

        return (

            <div>

                <p>{this.state.count}</p>

                <button type="button" onClick={this.incrementCount}>

                    Increment Count

                </button>

            </div>

        );

    }

}

Pretty complex… right? Now let’s review the same coded using a useState() hook in a functional component.

import React, { useState } from 'react';

const App = () => {

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


    const incrementCount = () => {

        setCount(count + 1);
    };

    return (

        <div>

            <p>{count}</p>

            <button type="button" onClick={incrementCount}>

                Increment Count

            </button>

        </div>
    );
};

The two may look the same, yet the latter can make a world of difference when you work with complex syntax. The need is to simplify what can be kept simple and react useState() enables us to do so.

Two Rules To Remember

Per React documentation, a developer must follow these rules while using the useState() hook:

  1. The placement of the hook should be right near the top of the component before executing any JSX.
  2. The hook must only be applied to functional components and won’t work in other types like classes.

What Data React useState() Hook Hold?

The useState can store any data type, and that is an added advantage as states in a class component can only hold an object. In contrast, a hook can hold an object, an array, a string, a boolean, or a number.

1. An Array

import React from "react";

const Dealership = () => {

  const cars = React.useState(["Honda", "Toyota", "BMW"])

  return (

    <h1>I’m a car dealership</h1>

  );
}

2. An Object

import React from "react";

const Dealership = () => {

  const storeCount = React.useState([

      Honda: 15,

      Toyota: 10,

      BMW: 5,

  });

  return (

    <h1>We have ${storeCount[0].Honda} Honda available in the dealership</h1>

  );
}

3. A String

import React from "react";

const Dealership = () => {

  const supplier = React.useState(["Importer"])

  return (

    <h1>We received new models from ${supplier[0]}</h1>

  );
}

4. A Boolean

import React from "react";

const Dealership = () => {

  const isOpen = React.useState("false");

  return (

    <h1>We’re ${isOpen[0] ? “Open” : Closed”}</h1>

  );
}

5. A Number

import React from "react";

const Dealership = () => {

  const clients = React.useState("200");

  return (

    <h1>We have ${clients[0]}</h1>

  );

}

Wrap Up

React useState() hook has made it easier and less complicated to manage data types in React. Before it, the only way to was via a class component.

However, with this, developers can now readily manage data types beyond objects in functions by adding a hook.

Also Read: How To Use useCallback In React – Step By Step Guide

react dev jobs



author

admin


Candidate signup

Create a free profile and find your next great opportunity.

JOIN NOW

Employer signup

Sign up and find a perfect match for your team.

HIRE NOW

How it works

Xperti vets skilled professionals with its unique talent-matching process.

LET’S EXPLORE

Join our community

Connect and engage with technology enthusiasts.

CONNECT WITH US