Skip to content

Latest commit

 

History

History
73 lines (51 loc) · 2.72 KB

immutable.md

File metadata and controls

73 lines (51 loc) · 2.72 KB
._   _       _            
| \ | | ___ | |_ ___  ___
|  \| |/ _ \| __/ _ \/ __|
| |\  | (_) | ||  __/\__ \
|_| \_|\___/ \__\___||___/

Immutable

Overview

Useful for equality checks - as easy as primitive checks like

var x = 10
var y = 10
x == y   //true
x === y  //true

but for objects and arrays, instead!

e.g.

var map1 = Immutable.Map( {a:1, b:2, c:3} )
var map2 = map1.set( 'b', 2 )
assert( map1.equals( map2 ) === true )

var map3 = map1.set( 'b', 50 )
assert( map1.equals( map3 ) === false )

This works perfectly with the shouldComponentUpdate lifecycle hook in React.

Can be done without libraries:

Object.assign( {}, oldObj, {key: update} )
array.concat( [newItem] )

But this is slow and takes up memory

Immutable.js is significantly faster, but does not have a native api like Object.key() or obj[ 0 ]

  • Must use obj.get( 'key' )
  • Also needs js-transit to serialize

Can use react-addons-update to "mutate" objs/arrays for parts of app that really need the perf

Watch Render 2016 - Lee Byron for an overview of fully immutable front-end.

  • All about Pure Functions, Immutability, Compositions
  • Models are data. If you need a collection, use something like Immutable.
  • Components are pure functions wrapping and managing mutable views (DOM, iOS, Android, Windows)

Pros

Enables fast shouldComponentUpdates and memoizable Selectors.

Records are a good match for your /models and work well with React's PropTypes.

Clearly draws the line between App-dependent components (has Immutable prop data) vs lib components (no Immutable prop data)

Cons

Your components will have to deal with Immutable.js props. Especially for presentational components, using immutable's api may be undesirable. This can be addressed with container components to convert Immutable to regular javascript, which is a hassle, but likely necessary.

Immutable.js increases bundle size (~60KB unzipped, I think)

Also seen discussions from facebook about performance issues on large projects. (TODO: find talk from Relay team talking about immutable perf issues)

Conclusions

I love the idea and features, but for now it is just too much of a bother to use. Would really like to see these primitives one day in javascript without a library!