Home > Article > Web Front-end > Detailed instructions for getting immutable.js_javascript skills
What is Immutable Data
Immutable Data refers to data that cannot be changed once created.
By using Immutable Data, we can more easily handle issues such as caching, rollback, and data change detection, simplifying our development.
Immutable Data in js
In JavaScript, we can simulate Immutable Data through deep clone, that is, every time the data is operated, a new data is deep cloned.
deep clone
/** * learning-immutable - clone-deep.js * Created by mds on 15/6/6. */ 'use strict'; var cloneDeep = require('lodash.clonedeep'); var data = { id: 'data', author: { name: 'mdemo', github: 'https://github.com/demohi' } }; var data1 = cloneDeep(data); console.log('equal:', data1===data); //false data1.id = 'data1'; data1.author.name = 'demohi'; console.log(data.id);// data console.log(data1.id);// data1 console.log(data.author.name);//mdemo console.log(data1.author.name);//demohi
Of course you may realize that this is very slow. As shown below, it is indeed very slow
immutable.js is an open source project by facebook, mainly to solve the problem of javascript Immutable Data, by referring to hash maps tries and vector tries Provides a more efficient way.
To put it simply, immutable.js solves the performance problem through structural sharing. Let’s watch a video first to see how immutable.js does it
When we have a set operation, immutable.js will only clone the parts above its parent level, leaving the others unchanged, so that everyone can share the same parts, which can greatly improve performance.
Everyone familiar with React.js should know that React.js is a framework with UI = f(states). In order to solve the update problem, React.js uses virtual dom, which modifies the dom through diff to achieve high efficiency. dom update.
Sounds perfect, but there is a problem. When the state is updated, if the data has not changed, you will also do a diff of the virtual dom, which creates waste. This situation is actually very common. You can refer to this article flummox
Of course you may say that you can use PureRenderMixin to solve it. PureRenderMixin is a good thing. We can use it to solve some of the above problems, but if you pay attention, you can find it in the documentation. See this tip below.
PureRenderMixin is just a simple shallow comparison and is not used for multi-layer comparison. What to do? ? If you do complex comparisons yourself, the performance will be very poor.
The solution is to use immutable.js to solve this problem. Because every time the state is updated, as long as there is a data change, PureRenderMixin can immediately determine the data change, which can greatly improve performance. You can also refer to the official documentation for this part Immutability Helpers
The summary is: use PureRenderMixin + immutable.js