skip to Main Content

Trust you are having a great day!

I’m running into a serious issue with React. I have a state which holds an array. In a function I copy the state into a new variable. When I modify this newly defined variable it also updates the state which is not what I want.

Example:

const [arrayState, setArrayState] = useState(
    [
        {
            id: 'ID_1'
            text: 'item 1',
        },
        {
            id: 'ID_2'
            text: 'item 2',
        },
        {
            id: 'ID_3'
            text: 'item 3',
        },
        {
            id: 'ID_4'
            text: 'item 4',
        },
    ]
);

const myFunction = () => {
    let myVariable = [...arrayState];

    myVariable[1].text = 'myVariable item 2'; // This is modifying arrayState as well which is wrong

};

I only want myVariable to be modified and not my state (arrayState) as well.

2

Answers


  1. It has to do with primitive and reference values. Arrays or objects do not store values, but refer to addresses in memory where values ​​are stored. A simple example,

    const func = () => {
        // Same memory reference
        const temp = arrayState;
        temp[1] = "4";
        setAttayState(temp);
    }
    

    above code dont re-render because of referenece of value is not changed.

    you have to assign new reference address like,

    const func = () => {
    
        // Create new reference
        const temp = [...arrayState];
        temp[1] = "4";
        setAttayState(temp);
    }
    
    Login or Signup to reply.
  2. You can use structuredClone to make a deep clone of the array of objects.

    let myVariable = structuredClone(arrayState);
    

    Alternatively, a solution that only works for this specific data structure:

    let myVariable = arrayState.map(o => ({...o}));
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search