Skip to content
Advertisement

Any method to use single useState()

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.

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");

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

// somewhere in your code, This is important
setState((pre) => ({ ...pre, firstName: "John", email: "ab@gm.co" }));
Advertisement