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?