aLex
aLex

Reputation: 1

When does it make sense to use Immutable.js in React?

I've read that Immutable.js only make sense if you have a deep tree comparison to make. So I am assuming in the case where my application state looks like this:

const taskList = [
{
    name: 'task 1',
    priority: '1',
    isDone: false

},
{
    name: 'task 2',
    priority: '1',
    isDone: false

},
{
    name: 'task 3',
    priority: '1',
    isDone: false

}
];

It's not very useful and it should look something like this to make it useful:

{ 
    "stuff": {
        "onetype": [
            {"id":1,"name":"John Doe"},
            {"id":2,"name":"Don Joeh"}
        ],
        "othertype": {"id":2,"company":"ACME"}
    }, 
    "otherstuff": {
        "thing": [[1,42],[2,2]]
     }
}

So that we can use shallow comparison like:

shouldComponentUpdate(nextProps) {

    return (this.props.name !== nextProps.name || this.props.priority !== nextProps.priority || this.props.isDone !== nextProps.isDone  );
}

instead of traversing the tree, which is expensive. But otherwise, is there any reason to use Immutable.js? The above works with taskList just fine. In which case is this really needed?

EDIT: I have been using lodash and I just heard that lodash takes mutability in mind, but I am not sure how it does the same thing as Immutable.js without immutables.

toggleTask(task) {
    const found = _.find(this.state.taskList, task => task.name === task);
    found.isDone = !found.isDone;
    this.setState({ taskList: this.state.taskList });
}

Upvotes: 2

Views: 493

Answers (1)

Jamsheed Kamarudeen
Jamsheed Kamarudeen

Reputation: 728

If your taskList which you are rendering is large and elements get updated very frequently, using immutableJS objects will prevent you from renrendering all the list elements.

For example. Lets say, there is a list of 1000 tasks, which is rendered on the page.Now you made another server poll (or push), and you get the same 1000 tasks with one of the tasks property isDone changed. So, if you simply replace the old tasksList array with new tasksList array, all react components will rerender as every item in the list is a new element and shallow compare fails and this, all lifecycle methods of each list item component gets triggered. But if your taskList was an Immutable List, then you do a taskList.mergeDeep(newTaskList), only the reference of the List and the one element that has updated is changed. Thus every other list item will not go past shallow compare except the task item that has changed.

Upvotes: 2

Related Questions