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

react prop value updates when state value changes

I have this react component that renders a child and passes one prop:

const Parent: FunctionComponent = ({ route }) => {
    const { routeProp } = route.params;
    const { passThisProp } = routeProp;

    return (
        <Child prop={passThisProp} />
    )
}

// these functions are in different files

const Child: FunctionComponent = ({ prop }) => {
    const [localValue, setLocalValue] = useState(prop)

    function updateProp(prop: string[][]) {
        const arr = [...prop];
        arr[i][j] = count.toString();
        return arr;
    }

    return ...
}

Inside of the Child component I have a mapped through prop which is an array of string arrays. The issue is when I update locally or localValue the prop value that I passed also updated.

I assume that shouldn’t be happening. Why is the state change of my local variable changing the parents prop it passed? Firstly I’m only assigning localValue to have an initial state of whatever value prop has, right?

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

How are they getting linked? I’ve never seen this before. I’ve checked over everything and I’m not updating the prop anywhere. Can anyone explain this?

>Solution :

The current approach to cloning is only cloning the outer array but is not cloning the inner ones. Clone the inner ones so Child gets its own clone:

// Clone entire 2D array
const arr = prop.map((innerArr) => [...innerArr]);

the current code:

// Shallow clone, only cloning outer array.
const arr = [...prop];

// `arr[i]` references original array from `Parent`, updates it
arr[i][j] = count.toString();
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