Sub topic 13
Persistent Data Structures and Immutable.js
This chapter assumes you have read the earlier chapters on nested updates, structural sharing, and reference equality. You should also be comfortable with ES modules and installing packages with npm. To run the examples, install the library with npm install immutable and run each snippet as an ES module, for example in a .mjs file.
So far, immutability has been something you do by hand. Spread syntax, map, filter, and Immer all build new plain objects and arrays, and they share structure only where you copy along a path. Persistent data structures take a different route. The collection type itself never changes in place, and every update returns a new version that shares most of its memory with the old one.
What "persistent" means
A persistent data structure is a collection that keeps every earlier version available after an update. "Persistent" here has nothing to do with saving to disk. It means old versions persist. You never get an in-place change, because the API offers none.
Plain JavaScript objects can be used immutably, but nothing stops a teammate from writing state.user.name = 'x'. With a persistent collection, set returns a new collection and the old one is untouched:
import { List } from 'immutable';
const v1 = List([1, 2, 3]);
const v2 = v1.push(4);
console.log(v1.size); // 3
console.log(v2.size); // 4
console.log(v1.toArray()); // [1, 2, 3]
console.log(v2.toArray()); // [1, 2, 3, 4]push on an Immutable.js List does not change v1. It returns v2. No method on the list mutates it, so this discipline holds for the whole codebase without anyone having to remember it.
How it works internally: tries and path copying
Copying a plain array of a million items to change one element costs a million slot copies. Persistent structures avoid that by storing data in a tree. They then copy only the nodes on the path from the root to the changed leaf. Earlier chapters called this structural sharing. Persistent structures build it into the data layout.
Immutable.js uses two main tree shapes:
Listis a bit-partitioned vector trie. Each internal node has up to 32 children. An index is split into 5-bit chunks, and each chunk picks the child at one level.MapandSetuse a hash array mapped trie (HAMT). The key's hash is split into chunks the same way, and each chunk picks a branch.
With 32-way branching the tree stays shallow. A list of 1,000,000 items is only 4 levels deep, because 32⁴ is about 1,048,576. An update therefore copies about 4 small nodes and shares everything else.
Strictly, updates cost O(log₃₂ n) rather than constant time. In practice that number is tiny, and the bigger cost is allocating the new nodes. List also keeps a separate tail buffer, so repeated push calls are usually cheaper than a full path copy.
The core API
Immutable.js offers List, Map, OrderedMap, Set, OrderedSet, Stack, Seq, and Record. Most code uses Map and List plus the "in" methods for paths:
import { fromJS } from 'immutable';
const state = fromJS({
user: { name: 'Ada', address: { city: 'London' } },
settings: { theme: 'dark' }
});
const next = state.setIn(['user', 'address', 'city'], 'Paris');
const renamed = next.updateIn(['user', 'name'], name => name.toUpperCase());
console.log(state.getIn(['user', 'address', 'city'])); // 'London'
console.log(renamed.getIn(['user', 'address', 'city'])); // 'Paris'
console.log(renamed.getIn(['user', 'name'])); // 'ADA'
console.log(next.get('settings') === state.get('settings')); // true, shared branchfromJS converts plain objects and arrays deeply into Maps and Lists. setIn and updateIn do the nested spread pattern from the "Updating Nested Data Immutably" chapter in a single call. They copy only the path they touch.
Value equality
Plain objects compare by reference only. Immutable.js collections also support value equality: two collections with the same contents are equal under equals or is, even when they are different objects.
import { Map, Set, is } from 'immutable';
const a = Map({ x: 1, y: 2 });
const b = Map({ x: 1, y: 2 });
console.log(a === b); // false, different objects
console.log(a.equals(b)); // true, same contents
console.log(is(a, b)); // true
const points = Set([Map({ x: 1 }), Map({ x: 1 })]);
console.log(points.size); // 1, value-equal maps are deduplicated
console.log(a.set('x', 1) === a); // true, setting the same value returns the same instanceThe last line matters for change detection. A no-op update gives you back the original reference, so the cheap === check from the previous chapters still works. equals is a deep comparison and can cost O(n). Immutable.js caches each collection's hash code to speed up repeated comparisons, but you should still treat equals as the slow path.
Batching with withMutations
Every push allocates new nodes. To build a large collection, batch the operations:
import { List } from 'immutable';
const big = List().withMutations(list => {
for (let i = 0; i < 100000; i++) {
list.push(i);
}
});
console.log(big.size); // 100000
console.log(big.get(42)); // 42Inside withMutations the library uses a temporary mutable copy (a "transient") that changes nodes it already owns. You get one immutable result at the end. Only some methods are safe inside withMutations: set, push, pop, shift, unshift, and merge. map and filter still return new collections, so the batching does nothing for them.
Records for fixed shapes
A Record defines a fixed set of keys with defaults and allows normal property access:
import { Record } from 'immutable';
const User = Record({ name: '', age: 0 });
const ada = User({ name: 'Ada', age: 36 });
const older = ada.set('age', 37);
console.log(ada.age); // 36
console.log(older.age); // 37
console.log(older.name); // 'Ada'
console.log(User({ name: 'Grace' }).age); // 0, the defaultRecords are the closest Immutable.js gets to plain objects in readability. A record ignores keys it does not define.
Gotchas and failure modes
Common traps:
- Shadowed globals.
import { Map, Set } from 'immutable'hides the built-inMapandSetin that module. Many teams writeimport { Map as IMap } from 'immutable'to avoid confusion. - Bracket access fails silently.
state.useron an ImmutableMapisundefined. You must callstate.get('user'). TypeScript catches some of these mistakes. Plain JavaScript catches none. - Iteration order. A plain
Maphas no guaranteed iteration order. UseOrderedMapwhen order matters, for example for form fields or sorted results. - Mixed trees.
Map({ list: [1, 2] })stores a plain, mutable array inside an immutable map.fromJSconverts deeply, but theMapandListconstructors convert only the top level. - Library boundaries. JSON APIs, form libraries, and most UI components expect plain data. Every boundary needs a conversion, and each conversion costs time and breaks reference identity.
- Bundle size. The library adds tens of kilobytes (minified) to your bundle, and you pay that whether you use one collection type or all of them.
Immutable.js compared with adjacent approaches
| Concern | Spread and array methods | Immer | Immutable.js |
|---|---|---|---|
| Data type | Plain objects and arrays | Plain objects and arrays | Custom collection classes |
| Enforcement | None, by convention | Frozen output (auto-freeze on by default) | Built into the API |
| Cost of one update in a large collection | O(n) for the copied level | O(n) for each copied level, plus proxy overhead | O(log₃₂ n) |
| Value equality | No | No | Yes, via `equals` and `is` |
| Interop with other libraries | Native | Native | Needs `toJS` and `fromJS` |
| Learning curve | Low | Low | Moderate, new API |
The update-cost row is where Immutable.js clearly wins. If you change one item in a list of 50,000 rows many times per second, spreading the array costs 50,000 slot copies each time. A persistent List copies a few 32-slot nodes. For a typical form state with twenty fields the difference is too small to measure, and the API cost dominates.
Decision criteria
Choose Immutable.js, or another persistent library, when most of these hold:
- Collections are large (thousands of items or more) and updated often.
- You need value equality, for example as keys in a
SetorMap, or for deduplication. - You want immutability enforced by types and APIs rather than by code review.
- Most of the code touching the data is code you own, so conversion boundaries are few.
Prefer plain objects with spread or Immer when the data is small or medium-sized, when it flows through many third-party libraries, or when new team members need to read the code quickly. Immutable.js is still maintained, and version 5 improved its TypeScript types. Even so, much of the ecosystem moved toward Immer and plain data, partly because plain data works with browser devtools and JSON without conversion.
Exercise
You have an Immutable.js List with 1,000,000 numbers and call list.set(500000, 0). Roughly how many internal nodes are newly allocated, and why is the cost far lower than spreading a plain array of the same size?
Show answer
About 4 nodes, one per level of the 32-way trie, since 32 to the power of 4 is about 1,048,576. Only the path from the root to the changed leaf is copied. Every other node is shared with the old version. Spreading a plain array copies all 1,000,000 slots.
Exercise
A React selector returns state.get('todos').toJS(), and the component wrapped in React.memo re-renders on every store update, even unrelated ones. Explain the cause and give a fix.
Show answer
toJS() builds a new plain array and new objects on every call, so the prop never has the same reference twice and the memo check always fails. Fix it by passing the Immutable List itself (whose reference stays the same when todos are untouched) or by memoizing the conversion on the List's reference, for example with a reselect selector whose input is state.get('todos').
Exercise
What do these two lines log, and why? const m = Map({ tags: ['a'] }); console.log(fromJS({ tags: ['a'] }).equals(m));
Show answer
false. The Map constructor converts only one level, so m holds a plain array under tags. fromJS converts deeply and holds a List there. A List and a plain array are not value-equal, and two separate plain arrays are compared by reference, so equals returns false.
Exercise
Your team's app state is a settings object with about 15 fields, edited through a third-party form library that reads and writes plain objects. Should you adopt Immutable.js? Justify using the decision criteria.
Show answer
No. The data is small, so O(n) spread copies are cheap. The form library needs plain objects, which forces toJS and fromJS conversions at a busy boundary. Value equality is not needed. Spread syntax or Immer gives the same safety with plain data and less overhead.