Does it exactly mean treating it as "read-only"?
For example, if the state is:
{
arr: arrData,
obj: objData,
aMap: mapData,
aSet: setData
}
For any of the four that has no change to it, we can keep it as is, but let's say 3 level down obj
, which is obj.b.c.d
, and this d
refers to an array, and we need to modify one entry in the array, then we need to make a copy of that array, modify the entry, and let the new state refer to it? But if d
refers to a new array, then c
needs to have a new d
, so c
needs to be a new object, and for the same reason, we need a new b
, eventually, a new obj
?
So it is
let objNew = {
...obj,
b: {
...obj.b,
c: {
...obj.b.c,
d: [...obj.b.c.d]
}
}
};
objNew.b.c.d[someIndex] = someNewValueOrObj;
And now objNew
can be returned and the old state was not modified in any way (was reading it only).
So if prevState
was the old state, and state
is the new state, we just need to make sure right before we return the new state, for prevState
, if we were to dump all the values out, it stayed the same as what was passed in, while the new state would dump out the values for our new state.