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

196
Vistas
What is difference between using inline spread operator in setState and declaring new object outside of method?

I was getting some weird behaviour in my app for selecting services on a page. The full logic isn't relevant as I managed to fix it but I don't understand why what I changed fixed it.

I save the selected services in a state variable:

const [selectedServices, setSelectedServices] = useState({});

I was then in an event handler updating them like so:

let newServices = { ...selectedServices, ...toChange };
setSelectedServices(newServices);

This gave me weird janky behaviour which usually happens when I am mutating the current state value instead of creating a new object. I played around with it and changed it to this:

setSelectedServices((prev) => { return { ...prev, ...toChange } });

This fixed it, it now works as expected but I have no idea why.

newServices is created with the spread operator so it should be a new object. I guess there is some difference with the scoping or something that makes the changes work better but I don't understand it.

Can someone explain to me the difference between assigning in these 2 ways?

about 4 years ago · Juan Pablo Isaza
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