0

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

Stackblitz example

radek79
  • 43
  • 9
  • `{ ...current }` only creates a shallow copy; you'd be mutating the state. You could also consider (1) Use separate state variables instead of putting them all into a single one, as React recommends for functional components (2) Using a class component instead wouldn't make things easier (functional components are usually preferred when possible) – CertainPerformance Nov 27 '22 at 23:28
  • It is indeed making a shallow copy, but why is this not a good idea to do, given that it works – radek79 Nov 28 '22 at 06:47

0 Answers0