What are the advantages of immutable data?

46 Views Asked by At

What are the advantages of using immutable libraries like immer.js or immutable.js? What is the difference between making changes to a draft of an object or making changes to a duplicate of the object?

Are there any performance differences (And why?) between the blocks of code below?

Edit: Changed the console.log order and the use the spread operator in the second block of code in response to vanowm comment.

const { produce } = require("immer");

let numArray = [1,2,3];

const nextState = produce(numArray, (draft) => {
  draft.push(4);
});

console.log(nextState); // [ 1, 2, 3, 4 ]
console.log(numArray); // [ 1, 2, 3 ]
let numArray = [1,2,3];

const nextState = ((array) => {
  let newArray = [...array]
  newArray.push(4);
  return newArray;
});

console.log(nextState(numArray)); // [ 1, 2, 3, 4 ]
console.log(numArray); // [ 1, 2, 3 ]
0

There are 0 best solutions below