DogZoro28
DogZoro28

Reputation: 33

I want to know if it is alright to create a shallow copy of a state that contains an array with objects

Let's say I have this as a state in react :

const [cars, setCars] = useState([]);
  1. The cars array contains this :

    [{id: 0, brand: 'BMW'}, {id: 1, brand: 'Audi'}];
    
  2. And I create a copy of this state :

    const carsCopy = [...cars];
    
  3. Now let's say I want to modify the brand property from the last object in the copied array:

    carsCopy[1].brand = 'Toyota';
    
  4. Now the thing is that doing so I mutated the original object that sits in the cars array because in the copy it points to the same objects in the memory;

  5. Is this ok or is a bad practice and should be avoided? Should I make a deep copy instead?

Upvotes: 0

Views: 23

Answers (0)

Related Questions