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?
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With