Home > Net >  Any method to use single useState()
Any method to use single useState()

Time:03-08

What I wanted to know ,that is there any method / technique to replace many useState() hook in one hook.

Like,

const [firstName, setFirstName] = useState('');
const [email, setEmail] = useState('');
const [age, setAge] = useState('');
const [people, setPeople] = useState([]);

Instead of writing the whole thing again and again , we define it any one of them.

CodePudding user response:

You can use the useReducer hook instead of useState.

This is their official docs on useReducer

CodePudding user response:

You can create a state object and use it.

Note: When you set state, make sure you merge with the previous state. don't just call setState("abc");

const [state, setState] = useState({ firstName: "", email: "" });

// somewhere in your code, This is important
setState((pre) => ({ ...pre, firstName: "John", email: "[email protected]" }));

CodePudding user response:

NO there isn't any way to define all that state using a single useState. unless you want to manage your state as a single object which you can define like this

const [state, setState] = useState({
    // key: value
});

There are advantage in keeping each state separate from other state. or you can simple use a class component instead of functional component where you can have all your state manage inside of a single object

By the way this bring some kind of head-hake for each state property update you have to rely on spread operator to avoid to replace the entire object with a single value instead of an object with properties

CodePudding user response:

This may be one possible solution to achieve the objective:

const [myObject, setMyObject] = useState({
  firstName: '',
  email: '',
  age: '',
  people: []
});

Also, when needing to update any of the props in the variable, something like this may be helpful:

const updateMyObject = (propName, propValue) => setMyObject(
  prev => ({
    ...prev,
    [propName]: propValue
  })
);

And, the update may be invoked like so:

<input
  id="firstName"
  value={myObject.firstName}
  onChange={(e) => updateMyObject('firstName', e.target.value)}
/>

NOTES:

  1. It is not my personal preference/choice to employ this method
  2. Please exercise caution when updating the people as it is an array.
  • Related