When to use .toJS() with Immutable.js and Flux?

chollier picture chollier · Jan 9, 2015 · Viewed 39.2k times · Source

I'm trying to use ImmutableJS with my React / Flux application.

My stores are Immutable.Map objects.

I'm wondering at which point should I use .toJS() ? Should it be when the store's .get(id) returns ? or in the components with .get('member') ?

Answer

Lee Byron picture Lee Byron · Jan 21, 2015

Ideally, never!

If your Flux stores are using Immutable.js then try to maintain all the way through. Use React.addons.ReactComponentWithPureRenderMixin to achieve a memoization performance win (it adds a shouldComponentUpdate methods).

When rendering, you may need to call toJS() as React v0.12.x only accepts Array as children:

render: function () {
  return (
    <div>
      {this.props.myImmutable.map(function (item) {
        <div>{item.title}</div>
      }).toJS()}
    </div>
  );
}

This have changed in React v0.13.x. Components accept any Iterable as children instead of only Array. Since Immutable.js implements Iterable, you are able to omit the toJS():

render: function () {
  return (
    <div>
      {this.props.myImmutable.map(function (item) {
        <div>{item.title}</div>
      })}
    </div>
  );
}