Sub topic 13
Persistent Data Structures and Immutable.js
This chapter assumes you already know how spread-based nested updates work and what structural sharing means. You should also be comfortable importing packages with ES modules. Here you will see how a library can build structural sharing into the data structure itself, so you no longer have to arrange it by hand.
What "Persistent" Means
A persistent data structure keeps its old versions when you update it. Every update returns a new version, and the earlier version stays valid and unchanged. Plain objects updated with spread work this way too, but only by convention. Nothing stops a teammate from writing state.user.name = 'x'.
Persistent data structures enforce the rule. They expose no mutating methods, so the only way to "change" one is to get back a new version. They are also designed so that each new version shares most of its internal memory with the previous one.
How It Works Internally
Immutable.js stores a List as a tree with up to 32 children per node, called a vector trie. A Map uses a related tree, a hash array mapped trie. When you update one element, the library copies only the nodes on the path from the root to that element. Every other subtree is reused. This technique is called path copying.
With 32-way branching, a list of a million items is only four levels deep. An update copies a handful of small nodes, not the whole collection. That is the main advantage over spread copies on large collections: spreading a 10,000-item array copies all 10,000 slots, while a persistent List copies a few nodes.
Using Immutable.js
Install the package with npm install immutable, then run the following as an ES module.
import { List, Map, fromJS, is } from 'immutable';
// Lists: every "change" returns a new List
const list1 = List([1, 2, 3]);
const list2 = list1.push(4);
console.log(list1.size); // 3
console.log(list2.size); // 4
// Nested data: fromJS converts plain objects and arrays deeply
const state = fromJS({
user: { name: 'Ada', address: { city: 'London' } },
settings: { theme: 'dark' }
});
const next = state.setIn(['user', 'address', 'city'], 'Paris');
console.log(state.getIn(['user', 'address', 'city'])); // 'London'
console.log(next.getIn(['user', 'address', 'city'])); // 'Paris'
console.log(next.get('settings') === state.get('settings')); // true, shared
// Value equality, not just reference equality
const m1 = Map({ a: 1 });
const m2 = Map({ a: 1 });
console.log(m1 === m2); // false
console.log(is(m1, m2)); // true
// Back to plain JavaScript
console.log(next.toJS().user.address.city); // 'Paris'Compare setIn with the spread version of the same update from the nested-data chapter. You give a key path instead of rebuilding each level yourself, and sharing of the unchanged branches happens automatically.
Common Errors
| Mistake | What happens | Fix |
|---|---|---|
| Reading with `state.user` | Returns `undefined`, because data lives behind methods | Use `state.get('user')` or `getIn` |
| Calling `toJS()` on every render | Builds a fresh deep copy each time, so reference checks always fail | Convert once at the boundary, or read with `get` |
| Mixing plain objects inside a `Map` via `set` | The nested plain object stays mutable and isn't converted | Use `fromJS` or `Map(...)` for nested values |
| Importing `Map` and shadowing the built-in | Code that expects the native `Map` breaks | Import as `Map as IMap` |
Exercise
You have const s = fromJS({ a: { b: 1 }, c: { d: 2 } }) and run const t = s.setIn(['a', 'b'], 5). What do t.get('c') === s.get('c') and t.get('a') === s.get('a') print, and why?
Show answer
The first prints true, because the c branch is not on the updated path and is shared. The second prints false, because path copying created a new a node to hold the new value of b.
Exercise
Why is updating one element in a 100,000-item Immutable.js List cheaper than updating it with spread on a plain array?
Show answer
Spread copies all 100,000 slots into a new array. The List is a 32-way trie about four levels deep, so the update copies only the few nodes on the path to that element and reuses everything else.