JS

Everything You Need To Know About useState in React

useState hook in react
useState hook in react

React is a popular JavaScript library used to build user interfaces. One of the core features of React is its ability to manage state, or the data that represents the current state of an application. In order to manage state in React, developers use a hook called useState.

What is useStae in React?

useState is a built-in React hook that allows developers to add state to functional components. It works by providing two values: the current state and a function to update the state. When the state is updated, React will re-render the component with the new state.

Here is an example of how useState can be used in a React component:

import React, { useState } from 'react';

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

  function handleClick() {
    setCount(count + 1);
  }

  return (
    <div>
      <p>You clicked {count} times</p>
      <button onClick={handleClick}>
        Click me
      </button>
    </div>
  );
}

In this example, the Counter component uses the useState hook to add state to the component. The initial value of the state is set to 0 using the useState function. The function also returns a variable count that holds the current value of the state and a function setCount that is used to update the state.

The component also has a button that when clicked, calls the handleClick function. This function uses the setCount function to update the value of the count variable by adding 1 to its current value. When the state is updated, React will re-render the component with the new value of count.

Using useState in this way allows developers to easily add state to functional components without needing to convert them to class components. It also provides a simple and concise syntax for updating state.

Another common use case for useState is to manage form input data. Here is an example of how useState can be used to manage form data:

import React, { useState } from 'react';

function Form() {
  const [name, setName] = useState('');
  const [email, setEmail] = useState('');

  function handleSubmit(event) {
    event.preventDefault();
    console.log(name, email);
  }

  function handleNameChange(event) {
    setName(event.target.value);
  }

  function handleEmailChange(event) {
    setEmail(event.target.value);
  }

  return (
    <form onSubmit={handleSubmit}>
      <label>
        Name:
        <input type="text" value={name} onChange={handleNameChange} />
      </label>
      <label>
        Email:
        <input type="email" value={email} onChange={handleEmailChange} />
      </label>
      <button type="submit">Submit</button>
    </form>
  );
}

In this example, the Form component uses the useState hook to manage two pieces of form data: name and email. The initial values of both pieces of data are set to an empty string using the useState function.

The component also has two functions, handleNameChange and handleEmailChange, that are called whenever the user types in the input fields. These functions use the setName and setEmail functions to update the values of the name and email variables with the current input values.

Finally, the component has a handleSubmit function that is called when the user submits the form. This function prevents the default form submission behavior and logs the values of name and email to the console.

Using useState to manage form data allows developers to easily capture and use the data entered by users in their applications.

Here are some real-world scenarios where useState can be used to build dynamic user interfaces:

Toggle Buttons

A common scenario where useState can be used is to create toggle buttons. For example, consider a UI that has a button to toggle the visibility of a menu. The state of this button can be managed using useState. When the button is clicked, the state can be toggled to show or hide the menu.

Form Input Fields

Another common use case for useState is to manage form input data. In a form, there can be various input fields like text input, radio buttons, checkboxes, and select dropdowns. Each of these input fields can be managed using a separate useState hook. When the user types into an input field, the state can be updated to reflect the current value.

Modals

A modal is a common UI element used to display additional content or options within an application. When a modal is opened, the state can be updated using useState to reflect its current visibility. Developers can use the useState hook to manage the visibility state of the modal and update the state when the user opens or closes it.

Pagination

Pagination is a common UI pattern used to display a large list of items in smaller, more manageable chunks. In a pagination system, the current page number can be managed using the useState hook. When the user clicks on a page number, the state can be updated to reflect the current page, and the list of items can be re-rendered with the updated state.

Theme Switching

An application can allow users to switch between different color themes(Example : Light Mode and Dark Mode), which can be managed using useState. The state can be updated to reflect the user’s choice of theme, and the UI can be updated accordingly.

In conclusion, useState is a powerful and versatile hook in React that can be used in a variety of real-world scenarios. By using useState, developers can build dynamic and interactive user interfaces that respond to user interactions and input.

Happy Coding 🙂

About the author

Vishwas

A coder who is trying to solve some problems via "Procoders", Software Engineer By Profession, WEB Enthusiast, Hobby Blogger. I love to share Tech Ideas and like to learn and explore new things and Technologies.

Add Comment

Click here to post a comment