I am currently diving into Redux waters and ever since I understood how simple of a concept the reducers are I have to say I am really excited.
However, the question I pose on the title is something that struck me as odd.
Since immutability of the state object is such a core pillar of Redux, shouldn't the .getState()
method return a copy of the currentState
, so that it is not exposed to the environment and thus impossible to mutate it?
Two reasons here: 1) in a proper Redux app, you never should attempt to mutate State directly, so getState()
result is only to be used via getters, so there's no need to waste time and cycles on copying; 2) in fact, it's not that easy to copy it the right way. Quoting the related discussion from the corresponding issue:
You'd have to due a deep object assign to truely destroy all references and we wouldn't want to do that, as you wouldn't be able to compare if a particular part of your state tree changed, which is incredibly useful in React via shouldComponentUpdate.
Still, one might decide it's beneficial to use an Object.freeze()
over retrieved state as a safeguard (against mutating such an object somewhere else). However, passing the resulting state around too much is rarely a good pattern (as mentioned in this answer).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With