0

I am new to Redux and was learning how to work with it and trying to get how it works behind the scenes. But, I faced the confusion with why we need to keep state immutable in Redux, I admit, there has already been asked a question close to mine Why should objects in Redux be immutable? but in there I couldn't find clear explanation on why we need to keep state immutable. For example, I have this code which mutates the state on button click and the below code works pretty fine even if I mutate state:

const initialState = {
  counter: 0
};

const reducer = (state = initialState, action) => {
  if (action.type === "INCREMENT") {
    return {
      counter: state.counter + 1
    };
  }
  return state;
};

export default reducer;

Please can you kindly explain why above code works fine even if I mutate state and why I need to make state immutable.

Dickens
  • 895
  • 3
  • 11
  • 25
  • 1
    I don't see anything in the code you posted that's mutating anything. – Joseph Sible-Reinstate Monica Oct 06 '19 at 17:45
  • @JosephSible, how about this, counter: state.counter + 1? – Dickens Oct 06 '19 at 17:46
  • You're not mutating the state object there. You're making a new state object, and its value of `counter` happens to be one more than the old state object's. – Joseph Sible-Reinstate Monica Oct 06 '19 at 17:47
  • State should be updated through pure functions. Pure functions by definition have no side effects. Mutating an object (i.e. state) via a function would break this abstraction, this is why reducers always return new objects. – Drew Reese Oct 06 '19 at 18:11
  • it would be mutation if you did `state.counter++; return state;` instead – skyboyer Oct 07 '19 at 08:41
  • Possible duplicate of [Redux: Why is avoiding mutations such a fundamental part of using it?](https://stackoverflow.com/questions/37531909/redux-why-is-avoiding-mutations-such-a-fundamental-part-of-using-it) – skyboyer Oct 07 '19 at 08:43

0 Answers0