What I wanted to know ,that is there any method / technique to replace many useState()
hook
in one hook
.
Like,
JavaScript
x
5
1
const [firstName, setFirstName] = useState('');
2
const [email, setEmail] = useState('');
3
const [age, setAge] = useState('');
4
const [people, setPeople] = useState([]);
5
Instead of writing the whole thing again and again , we define it any one of them.
Advertisement
Answer
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");
JavaScript
1
5
1
const [state, setState] = useState({ firstName: "", email: "" });
2
3
// somewhere in your code, This is important
4
setState((pre) => ({ pre, firstName: "John", email: "ab@gm.co" }));
5