Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

88
Vistas
Différence between only one state for variables or state for every one in react

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 ?

about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

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.

about 4 years ago · Juan Pablo Isaza Denunciar

0

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.

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda