Working with Multiple States in React

Working with Multiple States in React with Examples:

In this article, I am going to discuss Working with Multiple States in React with Examples. Please read our previous article where we discussed Listening to User Input in React. In the previous article, we have seen how we can get the value of the input field that is set by the user. Now, the question is what do we want to do with that value?

We want to make sure that we store it somewhere so that later when the form is submitted, we can use that value. Because we want to gather all the values for all the inputs and then combine them into an object when the overall form is submitted. And one way of storing that value and making sure that it survives, even if that function (component function) will be re-executed and the component will be re-evaluated, is to use state.

Storing Value Using State in React:

We can import the useState hook from React,

Working with Multiple States in React with Examples

We can call it at the beginning of the ExpenseForm function and set the state for this input. Initially, an empty string is passed because when this component is rendered for the first time, nothing was entered. Again, we can use array destructuring to get our two elements, which are the currently entered title and a function for updating the State i.e. enteredTitle, setEnteredTitle,

Working with Multiple States in React with Examples

The function for updating the State should follow the convention i.e., setEnteredTitle. Now, when we react to this event where the user enters something, we can just call setEnteredTitle and pass event.target.value as a parameter,

Working with Multiple States in React with Examples

This will be stored in our State. The component will always update when you update the State. But we’re doing it to ensure that we’re storing this in some variable which is kind of detached from the life cycle of this component function. So, it doesn’t matter how many times this component function may re-execute, this State is stored and survives.

There will be other ways of solving this as well but this works fine. And it has another advantage as we’ll need that State for updating and for re-rendering that component later. For the moment, we just use state to save the value.

Now we can do the same for the other two inputs. You should try this on your own as well. You should listen to the change events for the other inputs as well and store the state for those changes. Let’s add an event handler for other input as well.

Adding Event Listener for other Input Fields:

We can start by adding a new function ‘amountChangeHandler’. The logic is basically the same as titleChangeHanlder.

Adding Event Listener for other Input Fields

We want to make sure that the amountChangeHandler function gets triggered whenever the amount changes. So, on the input field of amount, we can add an onChange prop and point at the amountChangeHandler,

Adding Event Listener for other Input Fields

And before we add any code in there, we will add the third function for date input which is ‘dateChangeHandler’,

Adding Event Listener for other Input Fields

This should be triggered whenever the date changes. So, again, we have to add an onChange prop in the input field of date and point at the dateChangeHandler,

Adding Event Listener for other Input Fields

Now, all these inputs are wired up,

Adding Event Listener for other Input Fields

At this moment, nothing will happen. We have to store the state for the changes made here. This brings up one important question or maybe a problem that you encountered, how can you manage more than one State?

Adding Multiple States in React:

We can call useState more than once. Maybe you have tried that. We can have multiple states; multiple state slices or state pieces per component. And all these States inside of one in the same component will then also be totally separated from each other. So, let’s call useState again. So, extract the enteredAmount and setEnteredAmount function with array structuring.

Adding Multiple States in React

Adding Multiple States in React

So, here, we’ve got these two pieces of State which belong to the ExpenseForm component. We can update and read them individually. So, they work in a totally separate way. When we update the amount, this will not affect the title and vice versa. For the amountChangeHandler, we can call setEnteredAmount and pass event.target.value here as well,

Adding Multiple States in React

We can do the same for the date. We have to call useState and store an empty string here as well.

Adding Multiple States in React

By the way, we’re storing strings all the time and not a number here for the amount, because by default, whenever you listen to the change event for an input, if you read the value of that input element, it’ll always be a string. Even if it stores a number, it will be a number as a string. That’s why we initialize all states with a string. Here, for the date State, we have enteredDate and setEnteredDate. We can update the date state in the dateChangeHandler function,

Adding Multiple States in React

Now, we got these three State slices. You will see that quite a lot that you will have more than one state per component. You can have these separate states and update them separately and manage them separately. That is a key part of this entire State Concept React ships with. You can, and you often will have multiple States per component.

Full Code of ExpenseForm.js File:
import React, {useState} from "react";

import "./ExpenseForm.css";

const ExpenseForm = () => {

  const[enteredTitle, setEnteredTitle] = useState('');
  const[enteredAmount, setEnteredAmount] = useState('');
  const[enteredDate, setEnteredDate] = useState('');

  const titleChangeHandler = (event) => {
    setEnteredTitle(event.target.value);
  };

  const amountChangeHandler = (event) => {
    setEnteredAmount(event.target.value);
  }

  const dateChangeHandler = (event) => {
    setEnteredDate(event.target.value);
  }

  return (
    <from>
      <div className="new-expense__controls">
        <div className="new-expense__control">
          <label>Title</label>
          <input type="text" onChange={titleChangeHandler}/>
        </div>
        <div className="new-expense__control">
          <label>Amount</label>
          <input type="number" onChange={amountChangeHandler} min="0.01" step="0.01" />
        </div>
        <div className="new-expense__control">
          <label>Date</label>
          <input type="date" onChange={dateChangeHandler} min="2023-06-25" max="2025-12-31" />
        </div>
      </div>
      <div className="new-expense__actions">
        <button type="submit">Add Expense</button>
      </div>
    </from>
  );
};

export default ExpenseForm;

In the next article, I am going to discuss Using One State Instead Multiple States in React with Examples. Here, in this article, I try to explain Working with Multiple States in React with Examples. I hope you enjoy this Working with Multiple States in React article

Leave a Reply

Your email address will not be published. Required fields are marked *