Rewriting state in Redux

牧云@^-^@ 提交于 2019-12-22 11:10:19

问题


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.


回答1:


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-12457617

  • What is pure function?
    https://medium.com/javascript-scene/master-the-javascript-interview-what-is-a-pure-function-d1c076bec976

  • Why Redux need reducers to be "pure functions"
    https://medium.freecodecamp.org/why-redux-needs-reducers-to-be-pure-functions-d438c58ae468

  • Redux devtools: https://github.com/gaearon/redux-devtools



来源:https://stackoverflow.com/questions/46371129/rewriting-state-in-redux

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