One core concept in Redux is, states are immutable. However, I saw many examples, including in Redux docs using javascript Object.assign. Then, I saw this warning in MDN:
For deep cloning, we need to use other alternatives because Object.assign() copies property values. If the source value is a reference to an object, it only copies that reference value.
So, why using Object.assign if the whole point is immutability? Am I missing something here?
Immutability means: I (as a developer) never assign new values to object properties; either because the compiler does not allow it, the object is frozen or I just don't do it. Instead, I create new objects.
If you always keep in mind that you should not mutate objects, and obey it, you will never modify the contents of an existing object even if you shallow copied it beforehand instead of deep-copying it (modification of existing objects is what immuting code allows to prevent, because that makes the code's behavior more easily predictable).
Thus, to create immuting code, you do not need deep copying.
Why avoid deep copying?
Example of immuting code without the need for deep copy (behind the scenes, it uses Object.assign
):
const state = { firstName: 'please tell me', lastName: 'please tell me' }
const modifiedState = { ...state, firstName: 'Bob' }
Of course, you can do it wrong if you shallow copy instead of deep copy an object:
const state = { firstName: 'please tell me', lastName: 'please tell me' }
const modifiedState = state
modifiedState.firstName = 'Bob' // violates immuting, because it changes the original state as well
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With