title: In redux, why do we have to keep the state immutable in reducers?
body: <p>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?</p>
  
  <p>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:</p>
  
  <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
  <div class="snippet-code">
  <pre class="snippet-code-js lang-js prettyprint-override"><code>const reducer = (state = [], action) =&gt; {
   switch(action.type) {
    case 'BRING_UP_NEXT_IMAGE':
      state.push(state.shift());
      break;
    default: 
     return state;
   }
   return state;
  };</code></pre>
  </div>
  </div>
  </p>
  
  <p>The UI doesn't update because Redux detects the same state reference (for what it's worth).</p>
  
  <p>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:</p>
  
  <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
  <div class="snippet-code">
  <pre class="snippet-code-js lang-js prettyprint-override"><code>const reducer = (state = [], action) =&gt; {
   switch(action.type) {
    case 'BRING_UP_NEXT_IMAGE':
      state = state.concat(state.shift());
      break;
    default: 
     return state;
   }
   return state;
  };</code></pre>
  </div>
  </div>
  </p>
  
  <p>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.</p>
  
  <p>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?</p>