Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

reactjs

redux

I'm new to Redux - and I'm really trying to get the big picture of using functional programming to make unidirectional data more elegant.

The way I see it- each reducer is taking the old state, creating a new state without mutating the old state and then passing off the new state to the next reducer to do the same.

I get that not causing side effects helps us get the benefits of a unidirectional flow of data.

I just really don't get what is so important about not mutating the old state.

The only thing I can think of is maybe the "Time-Traveling" I've read about because, if you held on to every state, you could perform and "undo".

Question:

Are there other reasons why we don't want to mutate the old state at each step?

like image 860
Nick Pineda Avatar asked May 30 '16 18:05

Nick Pineda


2 Answers

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.

like image 108
Rico Herwig Avatar answered Sep 26 '22 21:09

Rico Herwig


The key of the "no-mutations" mantra is that if you can not mutate the object, you are forced to create a new one (with the properties of the original object plus the new ones).

To update the components when an action is dispatched, Redux connector checks if the object is different, not if the properties have changed (which is a lot faster), so:

  • If you create a new object, Redux will see that the object is not the same, so it will trigger the components updates.
  • If you mutate the objet that it is already in the store (adding or changing a property, for example) Redux will not see the change, so it will not update the components.
like image 34
Rocío García Luque Avatar answered Sep 23 '22 21:09

Rocío García Luque