So my code looks like this, where I have two same states state1
and state2
. Clicking on the "change" button will set the state of state1, but in fact, the value of both states are changed, showing by clicking on the "Show" button. What is causing this issue?
import React, { useEffect, useState } from "react";
interface Obj {
num: number
}
const App = () => {
const [state1, setState1] = useState<Array<Obj> | null>(null)
const [state2, setState2] = useState<Array<Obj> | null>(null)
useEffect(() => {
const a = [{num: 1} as Obj]
setState1(a)
setState2(a)
}, [])
return (
<div>
<button
onClick={() => {
if (state1 == null) return null
const temp = [...state1]
temp[0].num = 100;
setState1(temp)
}}
>
Change
</button>
<button
onClick={() => {
console.log(state1, '11');
console.log(state2, '22');
}}
>
Show
</button>
</div>
)
}
export default App