Redux: Why is avoiding mutations such a fundamental part of using it?

Working with immutable data structures can have a positive impact on performance, if done right. In the case of React, performance often is about avoiding unnecessary re-rendering of your app, if the data did not change.

To achieve that, you need to compare the next state of your app with the current state. If the states differ: re-render. Otherwise don’t.

To compare states, you need to compare the objects in the state for equality. In plain old JavaScript objects, you would need to deep compare in order to see if any property inside the objects changed.

With immutable objects, you don’t need that.

immutableObject1 === immutableObject2

basically does the trick. Or if you are using a lib like Immutable.js Immutable.is(obj1, obj2).

In terms of react, you could use it for the shouldComponentUpdate method, like the popular PureRenderMixin does.

shouldComponentUpdate(nextProps, nextState) {
    return nextState !== this.state;
}

This function prevents re-rendering, when the state did not change.

I hope, that contributes to the reasoning behind immutable objects.

Leave a Comment