If i'm having 3 variables to handle with useState in react is doing this:
const [ user , setUser ] = useState({
name : '',
phone : '',
age : ''
})
setUser({...user, phone: value})
Or this :
const [ phone , setPhone] = useState('')
const [ name , setPName] = useState('')
const [ age , setAge] = useState('')
setPhone(value)
Is there any différence in term of performance ? Which approach is more appropriate ?
CodePudding user response:
It depends on how you use them. If you use it in a form, it might be more convenient to have them in a single object. Technically, react has a watcher system that will only update what needs to be updated and therefore not re-render what hasn't changed. Here is a link to the official documentation that can help you understand when to use object based vs single state elements.
CodePudding user response:
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.