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
1 2 |
const original = ['zero', 'one']; const newArray = [...original]; |
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 💪
1 |
newArray[1] = '💩'; |
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.
1 2 |
name = 'richard' name = 'ricky' |
- 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.
1 2 |
a = ['ricky',25] a[1] = 41 |
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:
1 2 3 4 5 6 7 8 |
case ACTION_TYPE: { const allRaceCard = state.allRaceCard; // make some change in a deep nested property in allRaceCard return { ...state, // spread other properties of state object. We did not change them allRaceCard: [...allRaceCard] // created a new array (new reference!) along with our changes. } } |
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.