Introduction to the

Immer is an IMmutable library written by the author of Mobx. The core implementation is to use ES6 proxy to implement JS immutable data structure with minimal cost. It is easy to use, small size, ingenious design, and meets our needs for JS immutable data structure.

Problem solved

Let’s say I have an object that looks like this

let myData = {
  b: {
    c: [2],
  },
}
Copy the code

When we do the following:

let a1 = myData; o1.p = 1; // myData is modified o1.p.x = 1; // myData has been modifiedCopy the code

Even with the expansion operator:

let a3 = { ... myData }; a3.p.x = 1; // myData has been modifiedCopy the code

The use of immer

import produce from 'immer';
let a4 = produce(myData, draft => {
  draft.p.x = 1;
})
Copy the code

Why not use light copy

Deep copy, but the cost of deep copy is high, affecting performance.