Set multiple state values with React useState hook

Viewed 19201

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?

3 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...

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.

Related