Immutable.js: Persistent Data Structures for JavaScript
It’s 2014, and as React gains traction, we're all starting to think more about "state management." The problem with plain JavaScript objects is that they are mutable. If you change a property, the whole object is different, making it hard for React to know exactly what needs to re-render.
Facebook just released Immutable.js, and it’s the solution we've been waiting for.
Why Immutability?
In a mutable world, you have to do deep comparisons to see if data changed. In an immutable world, if the reference is different, the data must have changed. This makes shouldComponentUpdate extremely fast.
Structural Sharing (HAMT)
You might think that creating a new copy of a 10,000-item list on every change would be slow. But Immutable.js uses Hash Array Mapped Tries (HAMT). When you "update" a list, it shares most of its structure with the previous version.
import { Map, List } from 'immutable';
// 1. Creation
const state1 = Map({
users: List([
Map({ id: 1, name: 'Alice' }),
Map({ id: 2, name: 'Bob' })
])
});
// 2. Update - creates a NEW reference, but shares memory!
const state2 = state1.setIn(['users', 0, 'name'], 'Alicia');
console.log(state1 === state2); // false
console.log(state1.get('users').get(1) === state2.get('users').get(1)); // true! (Shared)
The API
The API feels a bit like a mix of Clojure and Underscore.js. You use get, set, update, and merge.
const map1 = Map({ a: 1, b: 2, c: 3 });
const map2 = map1.set('b', 50);
map1.get('b'); // 2
map2.get('b'); // 50
In 2014, Immutable.js is the bridge between the imperative world of JavaScript and the functional world of efficient UI updates. It’s a must-have for any serious React project.