AboutBlogContact
TechnologyNovember 5, 2014 2 min read 32

Immutable.js: Persistent Data Structures for JavaScript (2014)

AunimedaAunimeda
📋 Table of Contents

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.

Read Also

Mojo: AI-Native Programming and Language Features (2024)aunimeda
Technology

Mojo: AI-Native Programming and Language Features (2024)

Is Python finally being replaced? Mojo combines the usability of Python with the performance of C++. Let's explore its unique ownership system.

Elasticsearch: The Hidden Cost of Segment Merging (2013)aunimeda
Technology

Elasticsearch: The Hidden Cost of Segment Merging (2013)

Why does your indexing speed drop suddenly? It's likely the Lucene segment merger working overtime. Let's tune it.

Dart: Google's Early Vision for a Structured Web (2011)aunimeda
Technology

Dart: Google's Early Vision for a Structured Web (2011)

Google just unveiled Dart at GOTO Aarhus. Is this the language that will finally replace JavaScript in the browser?

Need IT development for your business?

We build websites, mobile apps and AI solutions. Free consultation.

Get Consultation All articles