Search code examples
reactjsreact-state

Will the component re-render if i change the object property which is initialised with a state in react?


I have a state creditNote and before sending the payload to the api call, I am changing the payload and I can see the changed value for a second in my UI

creditNote state

const [creditNote, setCreditNote] = useState({
    invoiceNo: "",
    data: "Entire",
    creditNoteStatus: "pending",
    creditNoteDate: formatDate(new Date().toLocaleDateString()),
    creditNoteNo: "",
    remarks: "",
  });
const payload = creditNote;
const datearray = creditNote?.creditNoteDate.split("-");
payload.creditNoteDate =datearray[1] + "-" + datearray[0] + "-" + datearray[2];
const res = (await addEntireCreditNote(payload, category)) as any;

I am changing the payload only and not using the setState function so i should not be seeing the date changed in the UI. Even if it is changing the state, will it be causing re-rendering of the component.


Solution

  • Even if it is changing the state, will it be causing re-rendering of the component.

    No, because you are mutating the reference, it won't trigger a component rerender. With const payload = creditNote; the payload variable is a direct reference to the React state, and payload.creditNoteDate = ... is the mutation.

    You should avoid mutating React states at all costs.

    Create shallow copies of all state, and nested state, that you are updating.

    Example:

    const [first, second, third] = creditNote?.creditNoteDate.split("-") || [];
    
    const payload = {                                   // <-- new object reference
      ...creditNote,                                    // <-- shallow copy state
      creditNoteDate: [second, first, third].join("-"), // <-- overwrite property
    };
    
    const res = (await addEntireCreditNote(payload, category)) as any;