I'm learning how useState works deeply through the following component:
function MyComponent(){
const [ obj, setObj ] = useState({nested: {name: 'David'}, password: 'hello'});
const handleClick = () => {
setObj(prevObj => {
console.log(prevObj);
let newObj = { ...prevObj };
newObj.nested.name = prevObj.nested.name === 'David' ? 'Mary' : 'David';
return newObj;
});
}
return (
<div>
<button onClick={handleClick}>Press</button>
</div>
);
}
I understand that this could lead to problems in later stages because the state prevObj has been mutated in the line where I assigned newObj.nested.name to flip between the values 'David' and 'Mary'. Indeed it is a mutation because newObj.nested is the same in reference to prevObj.nested, which is part of the component state.
Given this understanding, I would still expect to see prevObj logged with property nested.name as 'David' on the first button click because that is the initial value, what the first 'previous value' would have been. However, this property has value 'Mary' instead. Why is this so?
Also, if prevObj.nested.name is 'Mary' as it is so, then wouldn't newObj.nested.name remain 'David' on button click by virtue of the assignment and ternary operator?
Note: if I console.log prevObj.nested I get an object whose 'name' property has value 'Mary' but if I console.log prevObj.nested.name I get the expected 'David'.
Thanks.