Home > Blockchain >  React updating props when I update the state that references to that props
React updating props when I update the state that references to that props

Time:07-18

I have a component which has an array props, and inside that component, I destructure that props to a useState. For example

function Field({myArray}) {
    const [tempArray, setTempArray] = useState([]);

    useEffect(() => {
        let temp = [...myArray];
        setTempArray(temp);
    }, [myArray])

}

Now, I have a function that updates the tempArray by setTempArray(someArray), now, when it updates, the myArray props also updates, why is that?

CodePudding user response:

Use deep copy https://developer.mozilla.org/en-US/docs/Glossary/Deep_copy

because a deep copy shares no references with its source object, any changes made to the deep copy do not affect the source object

function Field({ myArray }) {
  const [tempArray, setTempArray] = useState([]);

  useEffect(() => {
    let temp = JSON.parse(JSON.stringify(myArray));
    setTempArray(temp);
  }, [myArray])

}

  • Related