Search code examples
reactjsstatedestructuring

Can you make a copy of react state with destructuring?


If I need to make a copy of state to mutate in a function, do the following function the same?

const { mana } = this.state;
const mana = { ...this.state.mana };

Solution

  • Those do not do the same thing. The first line doesn't do any copying, it's just a shorthand for const mana = this.state.mana. Your second line makes a shallow copy of this.state.mana, and then assigns the new object to mana.