Home » React » Why Immutable ?

Why Immutable ?

React component use state and prop to render and it tracks changes of state and prop to re-render the component. There are many techniques to optimize the performance of re-rendering process and immutable is one of the technique.

How do you track changes in Javascript object ?

How do you track changes in Javascript object ?

The problem of object equality in Javascript.

It is hard to check the equality of objects in Javascript. Consider the following codes:

// Example 1:
var a = {message: 'Hello'};
var b = {message: 'Hello'};

console.log(a === b);

// Example 2:
var a = {message: 'Hi'};
b = a;
b.message = 'Hello';

console.log(a === b);

What do you think about the result of example 1 and example 2 ? Yes, the result of example 1 is false and result of example 2 is true.

In example 1, although the value of a & b are same but because they have different reference, the return result is false. In example 2, both a & b have same reference so the result is true.

In order to compare two objects in Javascript, we have to compare the value of every key in each objects. Now think about more complicated and nested objects. It’s such a pain to compare every keys in an object.

This is the problem Immutable can solve.

Introduce Immutable.js

Immutable.js is a open source library of Facebook. When you change a key in a immutable object, it will return a new object so it’s easier to track changes with immutability.

Now rewrite our example using Immutable.js:

// Example 1
var a = new Immutable.Map({message: 'Hello'});
var b = new Immutable.Map({message: 'Hello'});
console.log(a.equals(b)); // true
// Example 2
var b = a.set('message', 'Hello');
console.log(a.equals(b)); // true

// Example 3
var c = a.set('message', 'Hi');
console.log(a.equals(c));  // false

It is important that we use “equals” method to check object value instead of === because the === only checks object reference.

Now it’s easier to check comparison result and track changes on object.

Immutable.js also comes with other data structure like: List, Map, Set. All of methods from immutable object will result in return new object. For example: push, slice, set always return new object.

What is has to do with React ?

React component has state and prop, when component state or prop is changed. React must re-render the component. React provides shouldComponentUpdate which give developer control of the rendering process. By default, this method always returns true so React always render the component when there is any changes on state or prop.

We can use immutable and rewrite this method to control when React should re-render a component. With Immutable.js, it is easier for us to track changes on state or prop.

Other state management libraries like Redux also promotes the idea of immutable because with immutable, Redux store track changes easier and broadcast data to other component more efficient.