So, I'm just going through a React course. Learning this framework for the first time so this is likely a dumb question. Here's code I've been given for updating a property on an object stored in state as an array of objects.
const [squares, setSquares] = React.useState(boxes)
function toggle(clickedSquare) {
setSquares(prevSquares => {
return prevSquares.map((square) => {
return square === clickedSquare ? {...square, on: !square.on} : square
})
})
}
...but, the following code I wrote works too and seems simpler, what's wrong with this approach? State values are only shallow immutable. Objects stored in a state array are themselves mutable, as far as I can tell...
const [squares, setSquares] = React.useState(boxes)
function toggle(clickedSquare) {
clickedSquare.on = !clickedSquare.on;
setSquares(prevSquares => [...prevSquares])
}
Also consider this example where I have an array containing deeply nested objects held in state.
[
{
trunk: {
limb: {
branch: {
twig: {
leaf: {
color: "green"
}
}
}
}
}
}
]
I want to change that "green" to "brown". It states in this article Handling State in React that...
- Deep cloning is expensive
- Deep cloning is typically wasteful (instead, only clone what has actually changed)
- Deep cloning causes unnecessary renders since React thinks everything has changed when in fact perhaps only a specific child object has changed.
The thing that has changed in the tree example is just the leaf object. So only that needs to be cloned, not the array and not the whole tree or trunk object. This makes a lot more sense to me. Does anyone disagree?
This still leaves (no pun intended) the question of what bugs can be introduced by updating property values in a state array my way and not cloning the object that has the change? A single concrete example would be very nice just so I can understand better where I can optimize for performance.