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
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,
above code dont re-render because of referenece of value is not changed.
you have to assign new reference address like,
You can use
structuredClone
to make a deep clone of the array of objects.Alternatively, a solution that only works for this specific data structure: