Should you use Immer or Immutable.js to achieve immutability in your code? Check out this guide to make the right decision.

Immutability is not a new concept in programming. It serves as the basis for programming paradigms, such as pure functional programming. The whole idea is to avoid direct change to data after it has been created.

Below is a breakdown of what we’re going to discuss in this article:

  • Immutability in JavaScript
  • An introduction to Immer and Immutable.js libraries
  • A comparison between Immer and Immutable.js

Immutability in JavaScript

JavaScript primitives like strings and numbers are known to be immutable. This is true because strings, for instance, can’t be changed by any method or operation. You can only create new strings.

Let’s consider the variable below:

var name = "mark cuban"
name = "John Steve"

You could argue that the data is mutable because the name variable was reassigned to another string, but this is not the case.

Reassignment is different from immutability. This is because even though the variable was reassigned, it didn’t change the fact that the string “Eze Sunday” exists. It’s the same reason why adding 3 to 13 wouldn’t change the original variable 13, or you turning 18 doesn’t change the fact that you were 17 before.

Even though variables may be reassigned, the immutable data still remains the same.

We’ve established from the example above that primitives are immutable, but that isn’t the end of the story. There are data structures in JavaScript that are mutable. One of them is arrays.

To demonstrate this, let’s declare a variable and set its value to be an empty array as shown below:

let arrOne = []

We can easily update the content of the above array by using the .push() function:

arrOne.push(2)

This will add the data, 2, to the end of the array, altering the original array that we previously had.

Intro to the Immer and Immutable.js libraries

JavaScript wasn’t written for its data to be exclusively immutable, but there are instances where you need an immutable array or map to easily keep track or keep a record of changes in a data set.

This is evident in the React framework, especially when dealing with states and props. This is where immutability libraries kick in. These libraries help optimize our application, making it easier to track changes in our application. In this article, will be looking at two major immutability libraries. Namely, Immer and Immutable.js.

#javascript #programming #web-development #developer

Immer and Immutable.js: How Do They Compare?
2.65 GEEK