useState Hook in React

Introduction

The useState Hook allows functional components to have state variables. This function accepts the initial state as input parameters, returns a value reflecting the current state (which is not necessarily the initial state ), and a function to update it.

What Is UseState In React, And When Should We Use It?

The React framework provides multiple hooks that we can use in our applications. There are two hooks that we frequently use: useState and useEffect.

In UseState, one argument is taken at a time, the initial state, and two values return the current state and a state case. In the React dev tools, if we print the useState() function (console.log(useState)), we observe that it returns an array with the argument that the program provides.

For example, when creating a counter program or changing the text after clicking a button, UseState Hook can be helpful.

There are two types of components in React: Class and Functional Components. A class component is an ES6 class that extends React, and another is a functional component.  

Here’s the syntax for using useState in React. The State is the first element, and the function works as the second element.

const [state, setState] = useState(initialState)  

We pass the function as an argument whenever we calculate the initial state. This initial state relies on the function’s return value.

const [sum, setsum] = useState(function generateRandomInteger(){7=3+4);})  

In the above line function, the sum of numbers gets calculated and set as its initial state. The following code sample imports useState from react:

import React, { useState } from “react”  

The React library includes a built-in function called useState().

import { useState } from “react”;  

Functional components are the only ones that use useState().

Application constant = () => { 
    const [counter, setCounter] = useState(0); 
    // … JSX elements 
};  

Class components cannot use useState(). The return value of useState() is a tuple. An array’s first parameter is the value’s current state, and its second parameter is the function to update it.

What does React useState Hook do?

As explained previously, useState enables you to add a state to your component. When React.useState gets called by a program within a function component, it generates a single state corresponding to that function component.

While a class’s state is always an object, Hooks’ state can be any type. You can store any data type in the state, including objects, arrays, and booleans. The useState Hook is perfect for storing local component state, but it may need to work with other state management solutions for more complex projects.

Sample Code

The following code will help you understand how to implement the useState hook into your program.

import React, { useState } from “react”;
import ReactDOM from “react-dom”;

import “./styles.css”;

const Message = () => {
  const [message, setMessage] = useState(“”);

  return (
    <div>
      <input
        type=”text”
        value={message}
        placeholder=”Enter a message”
        onChange={e => setMessage(e.target.value)}
      />
      <p>
        <strong>{message}</strong>
      </p>
    </div>
  );
};

const rootElement = document.getElementById(“root”);
ReactDOM.render(<Message />, rootElement);

Conclusion

The hook (function) useState allows state variables to be used by functional components. This function takes the initial state as input and returns a variable with the current state value (not necessarily the initial state) and another function for updating it.

Related Posts

What are custom events in JavaScript?

Custom events are the events that allow you to decouple the code you want to run after a specific piece of code runs. There are various in-built events…

How to use nested for loop in JavaScript?

We use the for loop statement of JavaScript for repeating a set of statements inside the loop body a specified number of times. A nested for loop, as the…

What are the basic rules for JavaScript parameters?

A JavaScript function is a code that performs a particular task. The function parameters are the name list in the function definition. Parameters are also known as…

How to stop refreshing the page on submit in JavaScript?

Using event.preventDefault() to stop page refresh on form submit In this section, we will see how to use event.preventDefault() to stop page refresh on form submission. The event.preventDefault() restricts the default…

Target a Window Using JavaScript or HTML

TARGET attribute of HTML A link’s opening named frame or window is specified using the Target attribute of the <a> anchor tag. The concluding </a> tag in…

What is the role of deferred scripts in JavaScript?

Since JavaScript is a loosely typed language, you are not required to correctly predict the kind of data that will be kept in a variable. Depending on the information…