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?
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();