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.