-2

https://scrimba.com/scrim/co8364826b4423b1283ebbd24

function toggle(id) {
    const objIndex = squares.findIndex((obj => obj.id == id))
    const squaresHandler = squares
    console.log(squares)
    console.log(squaresHandler)
    squaresHandler[objIndex].on = !squaresHandler[objIndex].on
    console.log(squaresHandler)
    setSquares(squaresHandler)
    console.log(squares)

}

  • The short answer is that because `const squaresHandler = squares` does *not* create a copy, when you later do `setSquares(squaresHandler)` React literally cannot *react*, because `squaresHandler === squares` (it's the same array, referenced by two variables). You need to do `const squaresHandler = [...squares]` instead. – ChrisG Jun 01 '22 at 21:15
  • That's because JavaScript even if not explicit has *Pointers* and they are called references. When you do `const squaresHandler = squares` squaresHandler is pointing to the memory address where squares array is located, hence it is the same entity. React compares objects based on references, it doesn't do a deep equality check, so even if you are modifying squaresHandler, it sees it just like a pointer, pointing to the same object of squares and it doesn't trigger the reconciliation. – Cesare Polonara Jun 01 '22 at 21:46

0 Answers0