How to handle states in React

Working with the state and changing the state based on requirements is a fundamental part of React. There are various ways to work with the state while using React. We will talk about,

  • Handle multiple states
  • Handle multiple values in one state

First, let’s talk about handling multiple states in React.

Handling multiple states in React

In React, states are mostly used for storing values and changing the state of a particular portion of a website. Let’s take an example of a form; where the user may enter his name and his email address. And we want to store this data and use this data later. That’s where the state comes to play.

  • Open the app.js file which is inside the src folder.

import React, { useState, useEffect } from "react";
const App = () => {

  return (
    <div>

    </div>
  );
}

export default App

Note: To know about creating a react project and start working with one with Tailwind CSS, Please read this article.

  • Create a form with two input fields, inside the div.
<form className="card-body  my-20 p-0">

        <div className="form-control items-center lg:items-start">
          <input required type="text" placeholder="Text 1" className="input input-bordered w-full max-w-md " />
        </div>

        <div className="form-control items-center lg:items-start">
          <input required type="text" placeholder="Text 2" className="input input-bordered w-full max-w-md " />
        </div>

        <div className="form-control items-center lg:items-start mt-6">
          <button type="submit" className="btn btn-sm w-full max-w-md">Change Text</button>
        </div>
</form>

Here we have created a form that has two input fields. Our goal is to get the value from those input fields and store them in states.

  • Create a useState() hook to store the first input value.
 const [firstText, setFirstText] = useState('');

This useState() hook returns a value and a function to change that value. And by default, we are setting the value as an empty string. Because we will get the value from any input field as a string.

  • Add an onChange(), event listener, to the first input field and set the value to this state.
<input onChange={e=>setFirstText(e.target.value)} required type="text" placeholder="Text 1" className="input input-bordered w-full max-w-md " />

Hence, this onChange() listener will set the input value to that setFirstText()

In React, we can declare useState()  as much as we need. And change it based on the requirements.

  • Declare another state for the second input value and add an event listener to the second input field as well to hold the value.
const [secondText, setSecondText] = useState('');
<input onChange={e => setSecondText(e.target.value)} required type="text" placeholder="Text 2" className="input input-bordered w-full max-w-md " />
import React, { useState, useEffect } from "react";
const App = () => {
  const [firstText, setFirstText] = useState('');
  const [secondText, setSecondText] = useState('');
  return (
    <div className="mx-32">
      <form className="card-body  my-20 p-0">

        <div className="form-control items-center lg:items-start">
          <input onChange={e => setFirstText(e.target.value)} required type="text" placeholder="Text 1" className="input input-bordered w-full max-w-md " />
        </div>

        <div className="form-control items-center lg:items-start">
          <input onChange={e => setSecondText(e.target.value)} required type="text" placeholder="Text 2" className="input input-bordered w-full max-w-md " />
        </div>

        <div className="form-control items-center lg:items-start mt-6">
          <button type="submit" className="btn btn-sm w-full max-w-md">Change Text</button>
        </div>
      </form>
    </div>
  );
}

export default App

This is one way to handle a state; that is handling multiple states in React.

Handling multiple values in a single state in ReactJS

We can handle multiple values in a single state variable as well.

  • Declare a useState() hook with a default object to store the input values
const [textValues, setTextValues] = useState({
    firstText: "",
    secondText: ""
  });
  • Declare an onChange() event and a function to set the first input field’s value to the setTextValues() state.
<input onChange={handleFirstText} required type="text" placeholder="Text 1" className="input input-bordered w-full max-w-md " />
const handleFirstText = e => {
    setTextValues({
      ...textValues,
      firstText: e.target.value
    })
  };

Here, we have declared a function to store the input values. And we are using javascript’s spread operator to get whatever data has already been stored in the state and updating a specific one named, firstText with the values of the first input field.

  • Declare an onChange() event and a function to store the value and set it to the state just like in the previous step.
  const handleSecondText = e => {
    setTextValues({
      ...textValues,
      secondText: e.target.value
    })
  }
 <input onChange={handleSecondText} required type="text" placeholder="Text 2" className="input input-bordered w-full max-w-md " />

Let’s console.log the textValues state and check in the console if they are changing the states based on the input field values or not.

 console.log(textValues)
import React, { useState, useEffect } from "react";
const App = () => {
  /*  const [firstText, setFirstText] = useState('');
   const [secondText, setSecondText] = useState(''); */

  const [textValues, setTextValues] = useState({
    firstText: "",
    secondText: ""
  });

  const handleFirstText = e => {
    setTextValues({
      ...textValues,
      firstText: e.target.value
    })
  };

  const handleSecondText = e => {
    setTextValues({
      ...textValues,
      secondText: e.target.value
    })
  }

  console.log(textValues)
  return (
    <div className="mx-32">
      <form className="card-body  my-20 p-0">

        <div className="form-control items-center lg:items-start">
          <input onChange={handleFirstText} required type="text" placeholder="Text 1" className="input input-bordered w-full max-w-md " />
        </div>

        <div className="form-control items-center lg:items-start">
          <input onChange={handleSecondText} required type="text" placeholder="Text 2" className="input input-bordered w-full max-w-md " />
        </div>

        <div className="form-control items-center lg:items-start mt-6">
          <button type="submit" className="btn btn-sm w-full max-w-md">Change Text</button>
        </div>
      </form>
    </div>
  );
}

export default App

As we can see it also is working to handle the states.

Basically, whichever way we follow to set the state in state variables, it’s totally fine. It will work eventually.

So, these are the way that we can handle the states in React. With multiple states and multiple values but in single state.