There are others Stack Overflow threads that are kind of related to this question but very briefly answered. I wanted to create one that would more explicitly treat the problem that occurs when changing a state that's an object.
In the below code I'm updating on click the firstName property of user object, which is a state, but nothing is happening. Why is that?
export default function App() {
const [user, setUser] = useState({
firstName: "Jhon",
lastName: "Doe",
});
const changeFirstName = () => {
const newUser = user;
newUser.firstName = "David";
setUser(newUser);
};
return (
<div>
<div>
<p>First Name: {user.firstName}</p>
<p>Last Name: {user.lastName}</p>
</div>
<button onClick={changeFirstName}>Change First Name</button>
</div>
);
}