Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

280
Views
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
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!