I wonder why we should keep the state immutable in reducers. Is that mandatory or simply a recommended approach? Does redux take advantage of the immutability thing to do some optimization?
After some experiments, I find that redux does make use of this immutability thing. One evidence for that is when we return the same reference to the state from reducers, the UI doesn't get updated as it should, even if data inside the state has changed. As in the example below:
const reducer = (state = [], action) => {
switch(action.type) {
case 'BRING_UP_NEXT_IMAGE':
state.push(state.shift());
break;
default:
return state;
}
return state;
};
The UI doesn't update because Redux detects the same state reference (for what it's worth).
This explains the necessity that we must return a new reference to the state if we want to update the UI. But why Redux requires that the internal state structure should be immutable as well? From what I can see, whether the UI gets updated solely depends on whether the state reference itself is changed. Even if I mutate the internal structure, the app works normally as well, as in:
const reducer = (state = [], action) => {
switch(action.type) {
case 'BRING_UP_NEXT_IMAGE':
state = state.concat(state.shift());
break;
default:
return state;
}
return state;
};
Yes, I do mutate the previous state with "state.shift()", but since state.concat returns a new reference to the array, the state itself is a different reference and the app works normally.
In a nutshell, what I want to know is that whether the state should be strictly kept immutable is a necessity to make Redux function correctly, or a recommended option so that the app can achieve better performance by enabling shallow comparing in shouldComponentUpdate to bypass the reconciliation process?