to manage complex and nested objects and also if you have lots of states, it's better to use useReducer like this:
import { useReducer } from 'react';
const initialState = { name: '', phone: '', age: 0 };
const reducer = (state, action) => {
switch (action.type) {
case 'name':
return { ...state, name: action.payload };
case 'phone':
return { ...state, phone: action.payload };
case 'age':
return { ...state, age: action.payload };
default:
return state;
}
};
const LoginPage = () => {
const [state, dispatch] = useReducer(reducer, initialState);
const onChangeNameHandler = (e) => {
dispatch({type: 'name', payload: e.target.value})
}
return (
<input value={state.name} onChange = {onChangeNameHandler} />
)
}
And then you have all states in "state" that we define at first
ex:
console.log(state.name) // name
I suggest you read this article that compares both useReducer and useState here.