Домой United States USA — software Why Is Redux State Immutable?

Why Is Redux State Immutable?

163
0
ПОДЕЛИТЬСЯ

This blog covers an analysis of why the Redux state is immutable and how you should go about modifying the state in your Redux applications.
Join the DZone community and get the full member experience. For Redux to work correctly, the state must be immutable. This means that whenever we update the Redux state, we have to create a copy of the whole state and set values to fields we want to change. In code, this usually looks like this: In the code above, we are modifying the oldState ‘s field2 value by creating a new state and setting a new value to field2. The value and reference of oldState remain the same. Before we get into why we must change the Redux state in this way, we should know the difference between «value» and «reference.» The value of a variable is the «semantic» meaning of what that variable holds. For example, in the example code below, the semantics of what is held by var1 and var2 are the same, therefore we can say that their values are the same. However, var3 ‘s value is different since the «semantics» of what it’s holding is different. When we talk about reference, we are referring (pun intended!) to the memory address of where something is stored. So in the above example, the memory address of the object referenced by var1, is different from the memory address of the object referenced by var2. In other words, var1 points to a different memory address than var2. Therefore, their references are different, even though their values are the same! The only way two variables can have the same reference is when they are both pointing to the same memory address.

Continue reading...