DEV Community

Cover image for useState() Hook in React
Mrityunjay-Palled
Mrityunjay-Palled

Posted on

useState() Hook in React

In React, hooks are the special type of function that allows us to "hook into" React features. The useState() hook provides us with the ability to maintain state variables for the functional components. useState() causes a compnent to re-render whenever the value of the state variable changes

Importing useState() Hook in React App:

  import React, { useState } from "react";
Enter fullscreen mode Exit fullscreen mode

We can import the React useState() hook as shown above.

useState() Syntax:

 const[count,setCount]=useState(0)
Enter fullscreen mode Exit fullscreen mode

The useState() hook always takes an initial value, which in our case is 0. It always returns a state variable and a function to update a state variable; in our case, these two things are destructured into count and setCount, respectively.

Implementing a Simple Counter Using the useState() Hook:

import React, { useState } from "react";

const App = () => {

  const[count,setCount]=useState(0)

  const handleIncrement=()=>{
    setCount(count+1)
  }
  const handleDecrement=()=>{
    setCount(count-1)
  }
  return (
    <>
     <button onClick={handleDecrement}>-</button>
     <p>{count}</p>
     <button onClick={handleIncrement}>+</button>
    </>
  );
};

export default App;

Enter fullscreen mode Exit fullscreen mode

In the above example, as we can see, the initial value of the state variable count is set to 0. When the user clicks on the "+" button, the handleIncrement function is fired, which in turn calls the setCount() function to increment the value of count by 1. In a similar way, when the user clicks on the "-" button handleDecrement function is fired, which in turn calls the setCount() function to decrement the value of count by 1.

Building a Small project:

This small project takes book name and author as input from the user and returns them back when the user click on the submit button

Before Clicking the Submit Button:

Image description

After Clicking the Submit Button:

Image description

We are going to build the above project in two ways

  1. Using Multiple States
  2. Using a Single State

Using Multiple States:

import React, { useState } from "react";

const Book = () => {
  const [bookname, setBookName] = useState("");
  const [author, setAuthor] = useState("");
  const [submittedData, setSubmittedData] = useState({});

  const handleNameChange = (event) => {
     setBookName(event.target.value)
  };
  const handleAuthorChange = (event) => {
    setAuthor(event.target.value)
  };
  const handelSubmit = () => {
     setSubmittedData({
        bookname:bookname,
        author:author
     })
  };

  return (
    <>
      <div>
        <label>Book Name</label>
        <input
          type="text"
          onChange={handleNameChange}
        ></input>
      </div>
      <div>
        <label>Author</label>
        <input
          type="text"
          onChange={handleAuthorChange}
        ></input>
      </div>
      <div>
        <button onClick={handelSubmit}>Submit</button>
      </div>
      <br />
      <span>Book Name: {submittedData.bookname}</span>
      <br />
      <span>Author: {submittedData.author}</span>
    </>
  );
};

export default Book;


Enter fullscreen mode Exit fullscreen mode

In the above example, we are maintaining separate individual state variables, namely bookname, author, and submitData, for the corresponding actions.This is the simple and commonly used approach when working with the useState() hook.

Using a Single State:

import React, { useState } from "react";

const Book = () => {

  const [userData, setUserData] = useState({
    bookname: "",
    author: "",
    submittedData: {},
  });

  const handleNameChange = (event) => {
    setUserData((prev) => ({
      ...prev,
      bookname: event.target.value,
    }));
  };
  const handleAuthorChange = (event) => {
    setUserData((prev) => ({
      ...prev,
      author: event.target.value,
    }));
  };
  const handelSubmit = () => {
    setUserData((prev) => ({
      ...prev,
      submittedData: {
        bookname: prev.bookname,
        author: prev.author,
      },
    }));
  };

  return (
    <>
      <div>
        <label>Book Name</label>
        <input
          type="text"
          onChange={handleNameChange}
        ></input>
      </div>
      <div>
        <label>Author</label>
        <input
          type="text"
          onChange={handleAuthorChange}
        ></input>
      </div>
      <div>
        <button onClick={handelSubmit}>Submit</button>
      </div>
      <br />
      <span>Book Name: {userData.submittedData.bookname}</span>
      <br />
      <span>Author: {userData.submittedData.author}</span>
    </>
  );
};

export default Book;


Enter fullscreen mode Exit fullscreen mode

In the above approach we are maintaining the single state variable
to handle all the corresponding actions. If we take a closer look
at setUserData() function we are accessing value previous state and updating it with the new values.This type of approach can be used when we are heavily dependent on previous state values.

Top comments (0)