Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Redux: why using Object.assign if it is not perform deep clone?

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?

like image 545
yuval.bl Avatar asked Sep 03 '17 16:09

yuval.bl


1 Answers

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?

  • better performance of shallow copying
  • smaller memory footprint of shallow 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
like image 89
ideaboxer Avatar answered Sep 25 '22 03:09

ideaboxer