Rewriting state in Redux

Deadly 提交于 2019-12-06 01:07:35

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:

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!