In redux I understand that state is immutable and when you create new state you are essentially updating the object with what ever new information there is and then totally rewriting the state.
Today I had a thought and I am not sure how stupid it is.
Is it computationally expensive to keep re-writing the state? I know that this is one of the major paradigms of Redux, but I want to know if this makes sense from a memory and space perspective.
You are allowed to mutate the state in Redux but you should not do it at any cost because you'd be coding in Redux anti-patterns
Mutating objects, in vanilla JavaScript or in any framework, may bring many side-effects with it which could be very painful to debug. You should opt for pure functions unless its necessary to mutate.
Now back to Redux, functions in reducers should be pure functions. here is why:
Redux algorithm checks if a state has been updated by comparing the memory location of the previous and the next state.
Now, when you mutate an object in JavaScript, you are simply updating an existing object and therefore, the memory location remains the same and the store does not get updated. Mutating the state also disables an essential feature of Redux devtools, time-travelling to debug.
On the other side, if instead of mutating the object you create a new one, when redux compares the memory location of previousState (the state before you changed it) and the nextState(the new one which you sent), Redux at this point realises that there has been a change and it updates the store with you latest state.
References:
Redux anti-patterns: https://github.com/coodoo/react-redux-isomorphic-example/issues/9
impure functions and issues with Redux devtools:
https://github.com/coodoo/react-redux-isomorphic-example/commit/6998c46d3c1a102b5f1bfb4f9aa44e5e7f9f6e87#commitcomment-12457617What is pure function?
https://medium.com/javascript-scene/master-the-javascript-interview-what-is-a-pure-function-d1c076bec976Why Redux need reducers to be "pure functions"
https://medium.freecodecamp.org/why-redux-needs-reducers-to-be-pure-functions-d438c58ae468Redux devtools: https://github.com/gaearon/redux-devtools
来源:https://stackoverflow.com/questions/46371129/rewriting-state-in-redux