Reputation: 33
Let's say I have this as a state in react :
const [cars, setCars] = useState([]);
The cars array contains this :
[{id: 0, brand: 'BMW'}, {id: 1, brand: 'Audi'}];
And I create a copy of this state :
const carsCopy = [...cars];
Now let's say I want to modify the brand property from the last object in the copied array:
carsCopy[1].brand = 'Toyota';
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;
Is this ok or is a bad practice and should be avoided? Should I make a deep copy instead?
Upvotes: 0
Views: 23