Cloning Array the Right Way

ref – https://www.samanthaming.com/tidbits/92-6-use-cases-of-spread-with-array/

We want to clone an array, where changing a value in the new array does not affect the original array

original: [‘zero’, ‘one’]
newArray: [‘zero’, ‘one’]

So if we did this correctly, our original array shouldn’t be affected if we changed the newArray. Alright, let’s give this a try 💪

newArray is now: [‘zero’, ‘💩’]

original: [‘zero’, ‘one’] Great! original array is NOT affected

Using it in React’s Reducer

In React’s reducers, when we change property data of an array, React only does a value comparison of the object. If the two objects are different, it will update the DOM. If they stay the same, it doesn’t.

This works well for primitive values.

  • Are the two value’s Type same? √ string
  • Are the two values same? X one is richard, other is ricky

Update the DOM!!

But for objects it doesn’t work.

React literally does this: a === a

  • Are the two object’s Type same? √ Array
  • Are the two object’s values (in this case, address of the object) same? √

no change, no update of DOM. This is not what we want because we want the DOM to update so that we see age is 41, not 25.

No matter how much you change the object’s data, it will always stay the same if you do value comparisons.

In order to remedy this, we need to clone the array using spread syntax so that we get a new Array object (with its own address value) like so:

Now, React will do this:

  • Are the two object’s Type is Array? √
  • Are the two object’s address value same? X

Update the DOM!!!!

And this is exactly what we want.