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

167
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
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