Front-End Insights

Immutable.js with Redux, his best friend

ProgrammingRedux

In the previous post I wrote about, in my opinion, the best Flux implementation – Redux. If you read it carefully, you know that the state in Redux should be immutable. That’s why today I will show you a library which is very helpful in preventing objects from being changed accidentally – immutable.js. In the second part of the article we will discuss Immutable.js with Redux – I think these two libraries are made for each other.

The basics of Immutable.js

I think that the official website describes best what Immutable.js is:

Immutable data cannot be changed once created, leading to much simpler application development, no defensive copying, and enabling advanced memoization and change detection techniques with simple logic. Persistent data presents a mutative API which does not update the data in-place, but instead always yields new updated data.

Immutable.js provides many Persistent Immutable data structures including: List, Stack, Map, OrderedMap, Set, OrderedSet and Record.

As you can see, Immutable.js simply provides a handful of data structures which are immutable. You can’t change them but you have an API available which gives you the ability to manipulate them. For example: the API provides a set method – when you use it, it doesn’t only change a part of the object. Instead, you get a completely new object in place of the old one but with this particular part changed.

Let’s see a sample code using Immutable.js:

var value = Immutable.Map({ key: 1 });
console.log(value.get('key')); // 1

value.set('key', 2);
console.log(value.get('key')); // still 1

value = value.set('key', 2); // has to be re-assigned
console.log(value.get('key')); // 2

In the example above, I used one of the persistent immutable data structures: Map. Immutable’s Map structure is an unordered key-value pair collection. It’s not by accident that I used this particular object. We will use it in the next section of the article where we will discuss Immutable.js with Redux.

What is most important in the example is shown in lines 4 and 5. As you can see, I used the set API method to change the key to value 2. In the next line we can observe that the value object didn’t change after this operation. When you look at line number 7, you can see that we have to re-assign the whole object because the set method does not make any change in the original map: it just returns a new version of this object with the key value changed.

I think this is enough to understand how Immutable.js works. Basically, other data structures have a similar way of working. Now, let’s see how can we use Immutable.js with Redux!

Putting things together – Immutable.js with Redux

Ok, this is the time to get to the point of this article. As you may already know from my previous article, the Redux state should be immutable. Every time the reducer method has to change the state, it actually returns a whole new object with some part of it changed. Sounds familiar? This is exactly what Immutable.js does 😉

I think it is best to show everything by using an example. Let’s take a look at the reducer method from the previous article:

const reducer = (state, action) => {
  switch (action.type) {
    case 'INCREMENT':
      return { ...state, counter: state.counter + 1 };
    case 'DECREMENT':
      return { ...state, counter: state.counter - 1 };
    default:
      return state;
    }
};

const store = createStore(reducer, { counter: 0 });

We can re-write it easily to use Immutable.js with Redux:

const initialState = Immutable.Map({ counter: 0 });

const reducer = (state, action) => {
  switch (action.type) {
    case 'INCREMENT':
      return state.set('counter', state.get('counter') + 1);
    case 'DECREMENT':
      return state.set('counter', state.get('counter') - 1);
    default:
      return state;
    }
};

const store = createStore(reducer, initialState);

As you can see, I declared a new variable – initalState. We assigned the new Immutable.Map structure to the variable. Additionally we initialized it by the object with the counter property set to 0. If you look at the last line of the example, we passed it to the createStore method so now, the state uses the Immutable.js Map object.

What is also important, we have to now use the API. In line number 6 and 8, we use the set method which, as we already know, returns a new, changed version of the structure.

Thanks to Immutable.js the state can’t be changed accidentally. You have to use the API to make any change to the state. And if you try to use the API outside of the reducer (without calling the action), the state won’t change.

And that’s it – this is how you can use Immutable.js with Redux! Quite simple right?

Summary

I think the described library best fulfils all the Redux state needs. As you can see, using Immutable.js with Redux is very simple and that’s why I actually always use it in my React projects.

Related Post

I recommend Nozbe

Simply Get Everything Done

Get your tasks and projects done thanks to Nozbe system and apps for the Mac, Windows, Linux, Android, iPad and iPhone.

If you want to know more about Nozbe and its capabilities, please take a look at my article about this great application.