Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
586 views
in Technique[技术] by (71.8m points)

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

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...