Grant Herman Grant Herman - 6 months ago 26
React JSX Question

Is rewriting state computationally expensive in Redux?

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.

Answer Source

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 native 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.


Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download