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)
}