0

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.

  • Does this answer your question? [Is Chrome’s JavaScript console lazy about evaluating objects?](https://stackoverflow.com/questions/4057440/is-chrome-s-javascript-console-lazy-about-evaluating-objects) – Konrad Aug 16 '23 at 06:57
  • @Konrad thanks for pointing me in this direction. I was testing on codesandbox, maybe not the best place to test JavaScript console behaviour. So I will implement this locally and see whether or not the behaviour is expected. – Panhaboth K Aug 16 '23 at 07:10
  • 1
    It will work the same locally. If you want to know the real value of an object use `console.log(JSON.stringify(prevObj));` – Konrad Aug 16 '23 at 07:34

0 Answers0