0

I'm new to React and I'm wondering why the following code does not works

const Component = () => {

  var [person, setPerson] = useState({
    name: 'bob',
    age: 21,
    message: 'hello!'
  })

const changeName = () => { 

    person.name = 'brian'
    console.log(person) // {name: 'brian', age: 21, message: 'hello!'}
    setPerson(person)

  }

return <>
    <h5>{person.name}</h5>
    <button onClick={changeName}>change the name</button>
  </>

However, if I do it by other ways, like the following or using spread operator, it works:

const changeName = () => { 

    person = { 
      name: 'brian'
    }

    setPerson(person)
    
  }
  • 1
    because in the first version you're mutating the existing variable and passing back the same object reference. React looks at that, sees it's the same reference, so doesn't think it needs to rerender. – Robin Zigmond Dec 24 '21 at 22:39

0 Answers0