3 ms·
Yeah, generally what's needed for data updates is _nested shallow copies_, not a deep copy. I talked about this in the "Immutable Update Patterns" section of t
by acemarke 9y ago
Yeah, generally what's needed for data updates is _nested shallow copies_, not a deep copy. I talked about this in the "Immutable Update Patterns" section of the Redux docs [0], and the articles in the "Immutable Data" section of my React/Redux links list [1] give more examples of how to handle data immutably in JS.
There's dozens of immutable update utility libraries available [2]. The one that I'm really excited about right now is a new library called Immer [3], from MobX author Michel Weststrate. It uses ES6 proxies to let you write normal mutative code in a callback, then applies the updates immutably. It looks like it should simplify a lot of common immutable update use cases, like in Redux reducers.
[0] https://redux.js.org/docs/recipes/reducers/ImmutableUpdatePatterns.html https://redux.js.org/docs/recipes/reducers/ImmutableUpdatePa...
[1] https://github.com/markerikson/react-redux-links/blob/master/immutable-data.md https://github.com/markerikson/react-redux-links/blob/master...
[2] https://github.com/markerikson/redux-ecosystem-links/blob/master/immutable-data.md#immutable-update-utilities https://github.com/markerikson/redux-ecosystem-links/blob/ma...
[3] https://github.com/mweststrate/immer/ https://github.com/mweststrate/immer/
- littlestymaar 9y agoWhat's a nested shallow copy, and how is it different from a deep copy ?
- acemarke 9y agoA shallow copy means creating a new object (or array), where all of the fields or array values point to the same references as the original: const original = {a : {a1 : 42}, b : {b1 : 99} }; const shallowCopy = {...original}; console.log(shallowCopy.a === original.a); // true A deep copy means creating new objects at _every_ level of nesting: const deepCopy = _.cloneDeep(original); console.log(deepCopy.a === original.a); // false To properly do an immutable update for `original.a.a1`, you'd need to copy each level of nesting, and overwrite the fields in that chain: const updated = { ...original, a : { ...original.a, a1 : 123 } }; console.log(original.a === updated.a); // false console.log(original.b === updated.b); // true