Moment For Technology

Immutability for React

Posted on Aug. 1, 2022, 8:52 a.m. by Wendy Thomas-Wade
Category: The front end Tag: react.js The front end jquery Immutable.js

Dear: honeyBadger8, group: 912594095.

The introduction

Immutability-helper was introduced in the previous project because the data levels between copies and references were too deeply nested, and the copied values affected each other. I would like to share with you some summary of the use process. For why it is not immutable, please refer to the following analysis. This is @IT· Brother Flathead Union. I'm Su Nan, the chief pit filling officer.

How do you copy js objects/arrays? In the current prevailing ES6, ES6 will not be a bit embarrassed to say that they are the front end (in fact, I generally say that they are siege lions, chetu cubs ?), we think most of the first idea, as follows:

  • Object.assign- most convenient;
  • [...].- The most awesome;
  • JSON.parse,JSON.stringify- Perfect combination;
  • $.extend()- API leading the fashion trend in jQuery era;
  • The last thing I want to do is recursively implement one;

However, we usually use object. assign as a shallow copy. When the data nesting level is deep, it will be... Ha ha, Json. parse, stringify it should create a temporarily potentially large string and then access the parser, performance is slower. Then I discovered immutable data, and I used to like it very much, but as time went on I discovered that immutable data is a way to create data, change data, insert data, delete data, and so on. For a man of my Bohemian life and a love of freedom, a long time of restraint is intolerable; All say that if two people don't agree with each other, it can't go on for a long time. It may also be fate. One day later, they met their new lover in their casual stroll ————Immutability Helpers.

Well, today's topic is to share with you the usage of the Immutability Helpers API, tips and attention points. If you don't understand, please correct:

So excited that I almost forgot to add, a simple copy:

  // Implement a simple recursive copy of the data
  let customClone = (rawObj) = {
    let copyObj = {};

    for (var key in rawObj) {
      if( typeof rawObj[key] === 'object'[key]) ! = ='[object Array]'){
          copyObj[key] = customClone(rawObj[key]);
          copyObj[key] = rawObj[key];
    return copyObj;
  let objA =  {"name":"Jiangsu"."sex":"Male"."height":"176"};
  let objB =  customClone(objA);
      objB.signature = "Bao Jianfeng from honed out, plum blossom fragrance from the bitter cold, do the temperature of the siege lion.";


Copy the code

  • Added a Object.assignThe pit:
  let data = {
      organization:"@IT· The Flathead League",
      job:"Principal Pit Filling Officer",
  let data2 = Object.assign({},data);
  data2.children.age = 28;
  data2.children.job = "Chief whip officer.";
  data2.b = 666;
  console.log("I'm raw data data:",data);
  console.log("I am the copied data data2:",data2);

Copy the code

Last review of IMmutable

It is often said that when you marry someone new, you forget your old, but I am not an ungrateful man. Draw a full stop:

Again, I don't think immutable is bad or powerful enough, but I don't like it

Immutable data encourages pure functions (data-in, data-out) and lends itself to much simpler application development and enabling techniques from functional programming such as lazy evaluation.

  const list1 = List([ 1.2.3 ]);
  const list2 = List([ 4.5.6 ]);
  const array = [ 7.8.9 ];
  const list3 = list1.concat(list2, array);
  console.log(list3) // List {size: 9, _origin: 0, _capacity: 9, _level: 5, _root: null,... } -- list3.get(0)

Copy the code
  let data = fromJS({
  let data1 = {
    a:1.b:2.children: {name:"Jiangsu",}};let data2 = data.mergeIn(['obj'],data1,{c:Awesome!});
  console.log("Acquired data:",data2.getIn(['obj'.'c']));
  console.log("Here is the data created by formJS:",data2.getIn(['obj'.'children'.'name']));//

Copy the code

When immutable is used, all data must be selected one by one, not because it is bad or not powerful enough, but because it is not a JQuery selector that is similar to its syntax, such as get, getIn, set, List, etc. It can also be rolled back using the toJS method.

Immutability Helpers for

Its description on gitHub is simple: Mutate a copy of data without changing the original source -- changing a copy of data without changing the original source.

I became acquainted with it because it appeared in the React official document, and I was very much in love with it. Really, IT was only because I saw it in the crowd for a second and never forgot it. It is not immutable, because it does not restrict you by so many rules, gives you freedom, gives you independent space, and gives you independent thinking. Let you want to use, use that go ~ ~ (mud horse, how a little like Zhang Xiaolong said it's small program ?), but you rest assured, its pit is really less than small program, API is also very simple, the next look, its basic usage:

  • $push- array;
  • $unshift- array;
  • $splice- array;
  • $set-- Replace/overwrite/merge original data;
  • $toggle-- Array of strings, toggles a list of Boolean fields from the target object;
  • $unset-- Remove the list of keys in array from the target object;
  • $mergeMerge objects;
  • $applyPasses in the current value to the function and updates it with the new returned value;
  • $add- new;
  • $remove- delete.

The above is basically all its API, let's have a look, the specific use of it:


  • The name tells you what it does. It's like a nativepushSame, but written a little differently;
  let arr = [];
  let arr2 = update(arr,{
    $push : ["a"."b"."c"].// Use the [] symbol instead of the "A ";
    [4] : {/ /!!!!! Index, you can specify the value of the modified subscript
      $set:"I'm a substitute."}});console.log(arr2);
Copy the code


  • Same as the originalunshift, insert at the beginning of the original array, again written as an array;
  let arr = [];
  let arr2 = update(arr,{
    $unshift : ["a"."b"."c"],
    [4] : {$set:"I am Chief Pit Filling Officer, Sonny."  // It is important to note that the operation is performed before unshift, i.e. the search for the fourth subscript on the original arr}});console.log("Primitive array",arr);// [1, 2, 3, 4, 5, 66] does not affect each other
  console.log(arr2); //[" A ", "B "," C ", 1, 2, 3, 4, "I am Chief Pit Filling Officer ∙ Nan Su ", 66]
Copy the code


  • Note: Array cover array, start,end, insert data... ,;

  let arr = [];
  let arr2 = update(arr,{
    $splice : [[1.2[66788.99] and {a:123.b:"Jiangsu"}]], // or [0,1," insert from me ",88,89,90," array, object, string "]

  // More complex usage:
  let obj={
    name:"immutable".list: [1.2[].]};let obj2 = update(obj,{
      [2] :value= update(value,{
        $splice: [[0.2]]  // [90,55,44,3,22,55] = [44, 3,22,55]}}}));Copy the code


  • We've already shown that, in fact, it's a bit of a substitution. When there are duplicate values, it overwrites them, and if there are no duplicate values, it adds them to show a more complex scene, a deeper level of data, and it doesn't affect each other;
  let obj={
    name:"immutable".children: {address:"ShenZhen".hobby:"@IT· Crew Alliance - Front-end Development"}};let obj2 = update(obj,{
    $set : {name:"immutability-helper".other:"Other fields, such as wechat official account: honeyBadger8, bring you updated shares every week."}});let obj3 = update(obj,{
    name: {$set : "Jiangsu"
    children: {hobby: {$set:"Chief Pit Filling Officer - javascript"}}});console.log("Raw data :",obj); 
Copy the code


  • From the name, you should be able to guess what it means to switch;
  • Boolean Boolean value toggle if you are forced toNumbeR type 0, 1, then use the citation method should be careful;
  let obj={
  let obj2 = update(obj,{
    $toggle: ['b'.'a'."c"."d"]});console.log("Raw data :",obj);

Copy the code


  • It goes withSplice `; See the picture below:
  let arr = [];
  let obj={
    name:"immutable".children: {address:"ShenZhen".hobby:"Blog"}};let obj2 = update(obj,{
    $unset : ["name"].children: {$unset: ["address"]}});console.log("Raw data :",obj);

  let arr2 = update(arr,{
    $unset : [1]});console.log("arr2:",arr2,arr2.length);

Copy the code


  • $mergeWith our favoriteObject.assignSame as doing merge operations, but it's better thanassignA lot of good, deep copy, will not affect each other:
  let arr = [];
  let obj={
    name:"immutable".children: {address:"ShenZhen".hobby:"Blog".array: ["I'm not a programmer"."Let's get to know him."]}};let obj2 = update(obj,{
    children: {array: {$merge: {items: ["Once upon a time there was a mountain to sit on."."There's a temple in the mountains."]},
        $splice: [[3.0."There lived a little monk."]]}}});console.log("Raw data :",obj);

Copy the code


  • $applyPerform a function operation based on the current value to obtain the new value:
  • Pay attention to: It has to be onefunctionOh!
  let obj={
      items:["Once upon a time there was a mountain."Array: [1,2,3,4,5,6],}};let obj2 = update(obj,{
      $apply:(val)=("Principal Pit Filling Officer")
          console.log("Old value",val);
          return[3, 0."There lived a little monk."]
        $apply(val)=(val.reverse())) // must be a function}}}); console.log("Raw data :",obj);

Copy the code


  • $remove Must have a certainIf you useSet,MapArray created:
  • The value to be deleted must be composed of numbers. If the value does not exist, ignore it.$remove:[2,666], 2 will be deleted, 6 will be ignored;
  • This API is a bit strange, normal normal array [], such can not delete!! ;
  • Common errors are shown below:
  let obj={
    name:"immutable".children: {array:new Set([]),}};let obj2 = update(obj,{
    children: {array: {$remove: [2].}}});console.log("Raw data :",obj);
Copy the code


  • $addWith just nowThe add method also followses6 Map/SetThe methods of add are consistent:
  • Just be careful when writing, [[]], nested!
  let obj={
    name:"immutable".array:new Map([["a".1], ["b".2]]),};let obj2 = update(obj,{
    array: {$add: [["66".56]],}});console.log("Raw data :",obj);
  console.log("Obtain key A :",obj2.array.get('a'));

Copy the code

3. Immutability Helpers

  • You can also customize methods, such as defining one$trinocularMethod to determine the value in the array;
  • Just a simple example, more complex usage, you can explore oh go to official github ?
  update.extend('$trinocular'.function(proportion, original) {
    return  original  88 ? (original/proportion ): (proportion+original);
  letArray =,33,55,777,322,444,61,12,34,52,245 [56];let array2 =,v)=update(k,{
  console.log("Raw data :",array);
Copy the code

Summary: The above is the basic API usage, add some official examples, did not mention the combination of use, as well as the use of the process, some mistakes may occur, need to pay attention to the place, more customized advanced usage, interested students can know by themselves.

It may not be immutable, but it is simple and does not contain too many restrictions. If I understand something wrong, I am welcome to correct it. After all, I am just a baby -- a novice on my way! ?.

Below is I get a public, welcome attention, the article will be the first time, after update on public number, the reason is before share with two articles, actually copied by other members of the public and the ?, the other day to update at the time of publication, WeChat hint my article is not the original detection to the same article, baby that is cool ~ in my heart, Decisively appealed to the other party (it is a training school public account, good anger), made up the nuggets released the link and screenshot date, luckily finally won the lawsuit ?! ? ?

Author: jiangsu - chief filling holes officer links: honeybadger8. Making. IO/blog/communication: 912594095, Z: honeybadger8 original in this paper, the copyright of their respective owners or authors. Commercial reprint please contact @IT· Flathead brother alliance for authorization, non-commercial reprint please indicate the original link and source.

About (Moment For Technology) is a global community with thousands techies from across the global hang out!Passionate technologists, be it gadget freaks, tech enthusiasts, coders, technopreneurs, or CIOs, you would find them all here.