There's a great video on the benefits and implementations for immutable data, from Lee talk in React Conf 2015. As far as thinking about immutable data and React, I would find it worth watching.
Aside, here are a few of my own thoughts on this.
Code of terms
The more complex your condition, the more difficult it is to manage it with literals and a distribution operator. Imagine that instead of being flat, you had several levels of nested state:
const initialState = { core: { tracker: { activeTrackId: '', state: 'stopped' } } };
Although you can still use the spread operator, it starts to become tedious.
return { ...state, core: { ...state.core, tracker: { ...state.core.tracker, activeTrackId: action.state !== 'stopped' ? action.track._id : '', state: action.state } } };
Now let's look at the equivalent with Immutable.js.
import { Map } from 'immutable'; const initialState = Map({ core: Map({ tracker: Map({ activeTrackId: '', state: 'stopped' }) }) });
Then we can use a persistent API to make profound changes to the structure.
return state .setIn( ['core', 'tracker', 'activeTrackId'], action.state !== 'stopped' ? action.track._id : '' ) .setIn( ['core', 'tracker', 'state'], action.state );
It is worth mentioning that depending on the shape of your condition, it may make sense to split and nest your gearboxes instead.
Structural exchange
When you modify an object using ImmutableJS, it exploits the fact that it is implemented using a hashed vector that tries to share most of the structure between the old object and the modified version.
When you use the distribution operator to create new literals, you are forced to copy more data than you need to create a new object.
Security
You can eliminate a huge class of errors by ensuring that the object cannot be modified.
With a volatile state, you can pass a link to some other code that can change it. Mutation of an object is not a βmistakeβ, so you wonβt be told that it has changed and there will be no stack trace, which means that it is very difficult to determine where the mutation comes from.
Wherever your immutable objects go, they will be safe.
Performance
You can use immutable data structures to make more complex decisions about whether to update components or not.
shouldComponentUpdate(nextProps) { const oldProps = Immutable.fromJS(this.props); const newProps = Immutable.fromJS(nextProps); return !Immutable.is(oldProps, newProps); }
Although such sortings may seem expensive, they do not allow you to install or remove the DOM when objects have not changed.
This will be even more effective if your details themselves are immutable objects, since fromJS
will not need to recreate nested levels.