Show Mutate a copy of data without changing the original source Setup via NPM npm install immutability-helper --save This is a drop-in replacement for // import update from 'react-addons-update'; import update from 'immutability-helper'; const state1 = ['x']; const state2 = update(state1, {$push: ['y']}); // ['x', 'y'] Note that this module has nothing to do with React. However, since this module is most commonly used with React, the docs will focus on how it can be used with React. OverviewReact lets you use whatever style of data management you want, including mutation. However, if you can use immutable data in performance-critical parts of your application it's easy to implement a fast
Dealing with immutable data in JavaScript is more difficult than in languages designed for it, like Clojure. However, we've provided a simple immutability helper, The Main IdeaIf you mutate data like this: myData.x.y.z = 7; // or... myData.a.b.push(9); You have no way of determining which data has changed since the previous copy has been overwritten. Instead, you need to create a new copy of const newData = deepCopy(myData); newData.x.y.z = 7; newData.a.b.push(9); Unfortunately, deep copies are expensive, and sometimes impossible. You can alleviate this by only copying objects that need to be changed and by reusing the objects that haven't changed. Unfortunately, in today's JavaScript this can be cumbersome: const newData = Object.assign({}, myData, { x: Object.assign({}, myData.x, { y: Object.assign({}, myData.x.y, {z: 7}), }), a: Object.assign({}, myData.a, {b: myData.a.b.concat(9)}) }); While this is fairly performant (since it only makes a shallow copy of
|