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?
Let's look at the example you linked:
Yes, that's a shallow copy of
state
, creating a new object with everything from the old but with an updatedvisibilityFilter
. But if you're consistent about treating objects immutably, then it's fine if the new state and the old state share references to other immutable objects. Later, presumably, if you were to change something else, you'd follow the same pattern. At which point, the shallow copy we made above would continue to use the old one, and your new object would use the new one.If you apply immutability all the way down, a shallow copy at the level you're modifying and all its parent levels is all you need. In the example above, the modification is at the top level, so it's just the one copy.
But what if it were deeper? Let's say you had this object:
If you wanted to update
a
, that's just like the state example above; you'd do so with just one shallow copy ofobj
:or with spread properties (currently at Stage 3, usually enabled in JSX transpiler setups, will probably make ES2018):
But what if you just want to update
a1
? To do that, you need a copy ofa
and ofobj
(because if you don't copyobj
, you're modifying the tree it refers to, violating the principal):or with spread properties: