0

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?

Phil
  • 157,677
  • 23
  • 242
  • 245
DogZoro28
  • 23
  • 3
  • 3
    Yes, this is a bad practice. Avoid mutating the shared object. You don't need to make a deep copy though, it's enough to copy the array and the particular car object that you want to update. – Bergi Jul 25 '23 at 23:48
  • @Phil thanks, I should have known there is a good canonical question – Bergi Jul 25 '23 at 23:52
  • 1
    [`.with()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/with) is a good use case for this (just make sure you copy the object you're setting) – Nick Parsons Jul 25 '23 at 23:52
  • @NickParsons awesome link but needs the proviso that it requires Node.js 20 – Phil Jul 25 '23 at 23:54
  • 1
    Thanks @Phil - Yeah, its quite new at this stage. It should become more accessible as time moves on though (I imagine there are simple polyfills for it also :)) – Nick Parsons Jul 25 '23 at 23:56

0 Answers0