Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Shouldn't Redux's .getState() return a copy of the state object?

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?

like image 626
Dimitris Karagiannis Avatar asked Oct 19 '22 16:10

Dimitris Karagiannis


1 Answers

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

like image 183
raina77ow Avatar answered Oct 27 '22 09:10

raina77ow