Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set multiple state values with React useState hook

Tags:

reactjs

I would like to set multiple state values with React useState hook, so that I can I update them separately with useEffect hook. I have the following code:

import React, { useState } from "react";

const initialValues = {
  phone: "",
  email: ""
};

const App = () => {
  const [order, setOrder] = useState("");
  const [paid, setPaid] = useState(false);
  const [submitting, setSubmitting] = useState(false);
  const [loading, setLoading] = useState(false);
  const [data, setData] = useState(initialValues);

  return (
    <div className="App">
    </div>
  );
};

export default App;

But when I inspect the App with React DevTools, I see multiple "State" values for my hook, instead of "order", "paid", "submitting" etc.

Here is the link to my codesandbox.

Where is my mistake? How can I set multiple state values to update them separately later on?

like image 770
jupiteror Avatar asked Apr 08 '20 17:04

jupiteror


People also ask

Can you have multiple useState in React?

React state hooks are great for managing state locally, within a single component. I love how simple it all is. If there are more than one state variable you want to monitor, it's simple enough to add a second or third useState hook.

Can you use useState more than once?

You can use useState multiple times. In fact it's even recommended in the React docs. we recommend to split state into multiple state variables based on which values tend to change together.


2 Answers

You can make one state with useState hook and put every value there like this.

import React, { useState } from "react";

const initialValues = {
  phone: "",
  email: ""
};

const App = () => {
  const [state, setState] = useState({
     order:'',
     paid: false,
     submitting: false,
     loading: false,
     data: initialValues
  });
  // example of setting this kind of state
  const sampleChanger = () => {
     setState({...state, paid: true, order: 'sample'});
  }
// etc...
like image 103
Shotiko Topchishvili Avatar answered Oct 08 '22 20:10

Shotiko Topchishvili


There is nothing wrong with your solution. The name you give to those states is only local to your component when you destructure the array that useState returns. React does not know about the name you give to those elements in the array that useState returns. Don't worry about the generic name that shows up in dev-tools, just try your solution and you'll see it works.

For something that shows up in dev-tools, you could use useDebugValue.

like image 29
Olavi Avatar answered Oct 08 '22 19:10

Olavi