On using Immutable.js


I’ve been using Immutable.js for quite some time in my non-trivial React/Redux projects and it has been paying off. Beside Redux’s requirement of never mutating its state, the library provides other relevant features that were a deciding factor for me to start using it.

This article explains very well, what immutability is, why it is good or bad in building applications in JavaScript.

When I first heard of the library, which is developed by Facebook, I was reluctant to use it, waving it off with excuse like “Why using it if I can easily clone object/array with Object.assign/[].concat”. Those excuses were only consequences of me not taking a time to study it and what it provides. I only began to show appreciation for it only after reading few blog posts describing its other features. Features like Records or extended set of object/array (technically, they are called Map/List in immutable.js) methods besides map, filter, reduce. Those methods quickly replaced their equivalents from lodash.

Example of my practice for using Immutable.js in Redux goes like this:

  • When AJAX response is received, it is immediately turned into Map with Immutable.fromJS, which deeply converts object and array to Map and Lists. I have all API calls organized in single object so that I do that in only one file.
  • In reducer’s function definition state has initial value and if it’s an object, it is of Immutable.js type. When updating state I only derive from that state variable (I’m not manually replacing it).
  • When reducer returns new state, Redux dumps new state to React components and I convert Maps and Lists back into plain objects so that I can benefit from propTypes checks. Immutable.js though is still useful in components, for example in shouldComponentUpdate because we can do a == b and not worry about deep/reference equality (remember, with immutable.js a state change of object produces a new object that have new reference)