'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.
Solution 1:[1]
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.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | windowsill |
