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

166
Vistas
Setting a state using spread operator updates the state vs setting the same object not updating the state

I have an initial object called as initUser, it consists of initial fields of the user as follows

const initUser: UserProfile = {
    firstName: '',
    lastName: '',
    phone: '',
    email: '',
    // and so on
};

The object is very big, it has more than 30 fields in it. So while re initialising the state to its initial state, I did this

setUser(initUser);

Which didn't work.

But when I did this

setUser({...initUser});

It started to work, although the spread operator is very expensive as it makes the copy of the variable, so any idea why passing the variable is not working? Thank you in advance.

PS: The initUser is placed in another file and is imported correctly since its working properly in the spread operator.

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

0

React will only update when the reference of the object on state is updated. Since Object.is(initUser, initUser); // true React will skip updating because it thinks nothing has changed.

Using the spread operator creates a new object, and thus creates a new reference.

The spread operator is very cheap because it creates a shallow copy, all the objects inside initUser will keep their references.

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