Immutables aka Value Objects
Benefits
Making data changes this way (with ImmutableJS + Reducers), you get:
- Memory Efficiency - Structural sharing is efficient in memory
- Predictability - preventing in-place mutation eliminates entire classes of bugs
- Rendering Speed - The cost of detecting if two objects are deeply different is nearly free ("constant time")
Usage
We use ImmutableJS objects in reducers. Here's how to work with them.
First, remember that every 'mutation' of an immutable leaves the original unchanged, so we effectively are returned a new pointer, which should either be returned immediately, have more mutations chained onto it, or captured in a variable for future manipulation. If the reducer is more than just a single chain of calls, that's fine too - just make sure you return the final object reference that all the changes have been applied to as the final line of the reducer:
createReducer({
'Tree.setIn': (state, {path, object} ) => state.setIn(path, object) // return the changed object,
'Tree.other': (state, {object} ) => {
let val = object.get('field').size()
return state.set('field', val + 1) // need explicit return
}
}, new Immutable.Map()) // <- the initial value is immutable, so all future values will be as well.
Structural Sharing
Immutables are great because although they return new pointers, the contents pointed to are shared as much as they can be, as illustrated below:
let xs = { d: {b: {a: 1, c: 1}, g: {f: {}, h: 1}} }
let ys = xs.setIn(['d', 'g', 'f', 'e'], 2)
let ys = xs.updateIn(['d', 'g', 'f'], f => f.merge({e: 2}) )
{ d: {b: {a: 1, c: 1}, g: {f: {e: 2}, h: 1}} }
![]()
Exercise
- Given the above state tree, and the goal of processing an acceptance of a draw in a board game, we might write one of the following lines - Which one is it? And which of the following have bugs, and what are they?
a) let game = game.set('draw.status', 'accepted')
b) let game2 = game.setIn(['draw', 'status'], 'accepted')
c) let game2 = game.updateIn(['draw', 'status'], 'pending', 'accepted')
References
Rich Hickey - The Value of Values (YouTube, 30:00)
- Location Flexibility : https://youtu.be/-6BsiVyC1kM?t=1148
- Facts Are Values, Not Places: https://youtu.be/-6BsiVyC1kM?t=1206
The Revolution of Pure Views - How This helps our UIs