Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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}));
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading