React | Updating Objects in React with useState

1 min read
Starting Point
Here's a basic useState
setup:
Initial values
const [person, setPerson] = useState({
name: "peter",
age: 24,
hobby: "read books",
});
The Mistake If you try to update only one property like this:
setPerson({ name: "susan" });
You will lose the other values (age and hobby). Now person only has a name.
Solution
Use the spread operator to keep the existing values:
setPerson({ ...person, name: "susan" });
This copies the old person object and updates the name.
Complete Example
import { useState } from "react";
const UseStateObject = () => {
const [person, setPerson] = useState({
name: "peter",
age: 24,
hobby: "read books",
});
const displayPerson = () => {
setPerson({ ...person, name: "susan" });
};
return (
<>
<h3>{person.name}</h3>
<h3>{person.age}</h3>
<h3>Enjoys: {person.hobby}</h3>
<button className="btn" onClick={displayPerson}>
show susan
</button>
</>
);
};
export default UseStateObject;
Why It Matters
React needs to see a new object to know that something changed. That’s why we don’t just change person.name directly. Instead, we create a new object with the updated values.
Using the spread operator like this keeps your state updates safe and clear.
0
Subscribe to my newsletter
Read articles from Valencia Miyeon Jang directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
