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.
You can use the useReducer hook instead of .useState
This is their official docs on useReducer
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: "ab@gm.co" }));
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