Feeling a little dumb, I've been working with React for 2 years and always thought that you have to use setState with a new copy of the object to avoid mutating the state. However, this example mutates the state and uses setState with the same object reference without any issue.
Why does this work?
const { useState } = React;
const Counter = () => {
const [countObject, setCountObject] = useState({count: 0});
const onClick = () => {
countObject.count = countObject.count + 1;
setCountObject(countObject); // mutated object, same reference
}
return (
<div>
<p>You clicked {countObject.count} times</p>
<button onClick={onClick}>
Click me
</button>
</div>
)
}
ReactDOM.render(<Counter />, document.getElementById('app'))
