debitoor/dot-prop-immutable

Discussion: Mutation – Shallow / Deep copy

Closed this issue · 2 comments

Hey @debitoor, hope all is good!
This is not really an issue, more a question I'd say.


When I read the intro;

The motivation for this module is to have a simple utility for changing state in a React-Redux application without mutating the existing state of plain JavaScript objects.

..then I thought, ah, perfect. I can use this to update nested objects "without mutating the existing state" in my "React/Redux"-app. But I continued reading:

None of the functions mutate the input object. For efficiency, the returned object is not a deep clone of the original, but a shallow copy of the objects in the mutated path.

Not returning a deep clone of the original object is contradicting the earlier paragraph – since changing a shallow copy will mutate the existing object – and hence the state.

What are your thoughts on this? Did I miss something perhaps?

The dot-prop-immutable library ensures that objects on you changed path will be new objects and not just mutated ones. It does not, however, do a deep copy of the entire object for several reasons. Firstly a deep copy of a large object can be very expensive and will be quite excessive when used with something like redux where mutations happens very often. Secondly, in the case of redux, for which this module was created, a deep copy would prompt all components depending on any part of the state to re-render which can also be costly. Thus for performance reasons dot-prop-immutable only does a shallow copy, along with a shallow copy of the affected path, and do not deep copy the entire object, which is really all you need for something like redux.

Ah, when I read it now it makes sense. Thanks for clarifying @bifrost 👍