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

194
Views
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
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!