Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

206
Visualizações
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 à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda