Using Spread operator to update the state in react

Hi, does copying nested object using spread have different address (reference). We do that so react can know while rendering the dom that there is some change (because of the references are different). But the value we update remains the same since spread doesn’t work with nested keys?

Yes. You are creating a new object or array [by “spreading” the values from the original array]

Yes, but if the value is a nested array or object, and that is the thing that needs to be updated, you just spread that as well.

  return {
    nestedObject: {
      nestedArray: [NEW_VALUE, ...state.nestedObject.nestedArray],

This is clearly onerous, which is why:

  1. you should try to avoid deeply nested structures, and flatten everything out (there is a good article on this on the Redux documentation site), and
  2. immutablity libraries are often used with React if there is complex nested state that cannot be flattened out (which is common). Immer is the current goto (and if you use Redux it is built into the toolkit the Redux team released last year). Immutable-js is/was the most widely used.