How to STOP React state from being modified when modifying array set to state?

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.

>Solution :

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}));

Leave a Reply