If I have nested state like this:
const [state, setState] = useState({
id: 14,
email: "example@domain.com",
profile: {
name: "Horus",
bio: "Lorem ipsum dolor sit amet..."
}
});
why is it that at every level of the state, a new object must be created? Like this:
setState(current => ({
...current,
profile: {
...current.profile,
bio: newBio
}
}));
When it still works by creating a new top-most reference and updating the nested state without creating each child object, like this:
setState(current => {
let newState = { ...current };
newState.profile.bio = newBio;
return newState;
});
Are there any performance considerations I'm not thinking about? Why not just make life easier and do the latter? I know that if using classes and shouldComponentUpdate, this would make things easier, but how does this help with function components?
Other answers show that using spread operator at each level IS the answer, but they don't address WHY?
Thanks