Ilja Ilja - 6 months ago 100
React JSX Question

Advantages of using immutable.js over Object.assign or spread operators

So far most of "starter boilerplates" and some posts about react / redux I've seen encourage usage of immutable.js to address mutability. I personally rely on

or spread operators to handle this, hence don't really see advantage in immutable.js as it adds additional learning and shifts a bit from vanilla js techniques used for mutability. I was trying to find valid reasons for a switch, but wasn't able to hence I am asking here to see why it is so popular.


This is all about efficiency.

Persistent Data Structures

A persistent data structure keeps previous versions of itself when it is mutated by always yielding a new data structure. To avoid expensive cloning only the difference to the previous data structure is stored, whereas the intersection is shared between them. This strategy is called structural sharing. Hence persistent data structures are much more efficient then cloning with Object.assign or the spread operator.

Drawbacks of persistent data structures in Javascript

Unfortunately Javascript doesn't support persistent data structures natively. That is the reason immutable.js exists and that its objects differ greatly from plain old Javascript Objects. This leads to more verbose code and a lot of conversions of persistent data structures to native Javascript data structures.

The crucial question

When does the benefits of immutable.js's structural sharing (efficiency) exceed its disadvantages (verbosity, conversions)?

I guess the library pays off only in large projects with numerous and extensive objects and collections, when cloning of whole data structures and garbage collection gets more expensive.