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

281
Visualizações
React - useState not updating unless class object is duplicated

I am trying to update the state using the useState hook for React. However, I think I am using it incorrectly or at least not how it's intended.

I have a class which is initialised.

const [form, setForm] = useState(new Form());

I am then adding elements to this form:

const element = ...

setForm(form => ({
  ...form,
  elements: [
    ...form.elements,
    element
  ]
});

However, this doesn't seem to update the UI to reflect this change.

I have also tried the following:

setForm(form => {
  form.elements.push(element);
  return form;
});

The only way I can get it to work is doing the following and as you can imagine it becomes quite a mountain to climb as it's a bit all over the place:

const duplicated = JSON.parse(JSON.stringify(form));
duplicated.elements.push(element);
setForm(new Form(duplicated));

Is there a better approach to do this rather than having to duplicate the object everytime.

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