0

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.

nonopolarity
  • 146,324
  • 131
  • 460
  • 740

1 Answers1

0

Redux uses shallow equality to check whether the state has changed to trigger a render in React. If the references to the new state and the previous are the same, i.e. === returns true, Redux considers nothing has changed and simply returns from the reducer.

You will have to produce a new state value that is referentially different to the old one no matter how deep down in your state a value has changed.

I would suggest you consider using a library like immer to help you with that in an efficient way.