Should Redux.getState () return a copy of the state object?

I am currently diving into the Redux waters, and since I realized how simple the gearbox concept is, I have to say that I am really excited.

However, the question I ask in the title is what seemed strange to me.

Since the immutability of a state object is such a basic element of Redux, shouldn't the .getState() method return a copy of currentState so that it is not exposed to the environment and therefore cannot mutate it?

+5
source share
2 answers

Two reasons: 1) in the correct Redux application, you should never try to directly mutate the state, so the result of getState() should be used only through getters, so there is no need to waste time and cycles on copying; 2) in fact, it is not so easy to copy it in the right way. To quote an appropriate discussion of the related issue :

You will need to assign a deep object to really destroy all the links, and we would not want to do this, since you could not compare if some part of your state tree has changed, which is incredibly useful in React via mustComponentUpdate.

However, it can be decided that it is useful to use Object.freeze() on the restored state as protection (against mutating such an object elsewhere). However, passing the resulting state too much is rarely a good picture (as mentioned in this answer ).

+3
source

I think you are confusing the repository and the state that it contains with the state of the Component. These are two different concepts. When you call getState (), you get the state of the "this" component; You DO NOT modify it; however, you can change it with setState (), and this causes the component to be redrawn. Instead, when you are inside the gearbox and the action results in a gearbox change state, the return state should always be a new object.

0
source

Source: https://habr.com/ru/post/1242096/


All Articles