Updating Objects in State in React JS
Course: React JS Training
Topic: Updating Objects in State
Official Documentation: React – Updating Objects in State
1. Introduction to Updating Objects in State
In React JS, state is used to store and manage data that can change over time. State can contain strings, numbers, booleans, arrays, and objects. Objects are especially useful when a component needs to manage related information together, such as a user's name, email, age, address, or profile details.
Updating objects in state means changing the information stored in an object and displaying the updated information in the component. React recommends creating a new object with the updated values instead of directly modifying the existing state object.
For example, a user profile may contain a first name, last name, and email address. If the user changes their first name, we should update that property while preserving the other properties.
2. What Is an Object in JavaScript?
An object is a collection of properties stored as key-value pairs. Each property has a name, called a key, and an associated value.
Example:
const student = {
name: "Rahul",
age: 22,
course: "React JS"
};
console.log(student.name);
console.log(student.age);
Output:
Rahul
22
In this example, the student object contains three properties: name, age, and course. React components can store similar objects in state using the useState() Hook.
3. What Is State in React JS?
State is data managed by a React component. When state is updated correctly, React can render the component again to display the latest information.
The useState() Hook allows functional components to create and update state.
Syntax:
const [state, setState] = useState(initialValue);
- state: The current state value.
- setState: The function used to request a state update.
- useState(): The React Hook used to initialize state.
- initialValue: The initial value assigned to the state.
Example:
import { useState } from "react";
function Student() {
const [student, setStudent] = useState({
name: "Rahul",
age: 22
});
return (
<div>
<h2>Name: {student.name}</h2>
<p>Age: {student.age}</p>
</div>
);
}
export default Student;
Here, the student state stores an object containing the student's name and age. Both values are displayed in the component.
4. Why Do We Need to Update Objects in State?
Applications frequently need to update object properties when users interact with a website. Updating objects in state is useful in the following situations:
- Updating user profile information.
- Handling form inputs.
- Changing product details.
- Updating student records.
- Managing login and registration information.
- Updating application settings.
- Changing the status of a task.
For example, when a user changes their email address in a profile form, React should display the new email without unnecessarily removing the user's other details.
5. Understanding State Mutation
Mutation means directly changing the contents of an existing object instead of creating a new object. Although JavaScript permits object mutation, you should treat objects stored in React state as read-only.
Incorrect Example:
import { useState } from "react";
function Student() {
const [student, setStudent] = useState({
name: "Rahul",
age: 22
});
function updateName() {
student.name = "Amit";
setStudent(student);
}
return (
<div>
<h2>{student.name}</h2>
<button onClick={updateName}>
Update Name
</button>
</div>
);
}
export default Student;
Problem: The existing state object is modified directly. Passing the same object reference back to the state setter may cause React to skip the update because the reference has not changed.
Important: Do not directly modify objects stored in React state. Create a new object and pass it to the state setter.
6. Correct Way to Update an Object Using the Spread Operator
The object spread operator (...) copies the enumerable properties of an existing object into a new object. It allows you to update one property while preserving the other properties.
Syntax:
setObject({
...object,
property: newValue
});
In this syntax, ...object copies the existing properties, and property: newValue replaces the specified property in the new object.
Correct Example:
import { useState } from "react";
function Student() {
const [student, setStudent] = useState({
name: "Rahul",
age: 22
});
function updateName() {
setStudent({
...student,
name: "Amit"
});
}
return (
<div>
<h2>Name: {student.name}</h2>
<p>Age: {student.age}</p>
<button onClick={updateName}>
Update Name
</button>
</div>
);
}
export default Student;
Result: Initially, the name is Rahul and the age is 22. After clicking the button, the name changes to Amit, while the age remains 22.
7. Updating a Single Property in an Object
Sometimes, you only need to update one property of an object. The spread operator allows you to preserve all other properties.
Example:
const [user, setUser] = useState({
name: "Priya",
age: 24,
city: "Mumbai"
});
function updateCity() {
setUser({
...user,
city: "Pune"
});
}
After calling updateCity(), the city becomes Pune, while the name and age remain unchanged.
8. Updating Multiple Properties in an Object
You can update multiple properties simultaneously by specifying more than one updated property in the new object.
Example:
import { useState } from "react";
function UserProfile() {
const [user, setUser] = useState({
name: "Priya",
age: 24,
city: "Mumbai"
});
function updateProfile() {
setUser({
...user,
name: "Anjali",
age: 25,
city: "Pune"
});
}
return (
<div>
<h2>{user.name}</h2>
<p>Age: {user.age}</p>
<p>City: {user.city}</p>
<button onClick={updateProfile}>
Update Profile
</button>
</div>
);
}
export default UserProfile;
When the button is clicked, all three properties are updated together. Properties not specified in the update would retain their previous values because of the spread operator.
9. Updating Objects Using Previous State
When the next state depends on the previous state, you can pass an updater function to the state setter. React supplies the previous state value to that function.
Syntax:
setState(previousState => ({
...previousState,
property: newValue
}));
Example:
import { useState } from "react";
function CounterProfile() {
const [user, setUser] = useState({
name: "Rahul",
score: 0
});
function increaseScore() {
setUser(previousUser => ({
...previousUser,
score: previousUser.score + 1
}));
}
return (
<div>
<h2>{user.name}</h2>
<p>Score: {user.score}</p>
<button onClick={increaseScore}>
Increase Score
</button>
</div>
);
}
export default CounterProfile;
Explanation: The updater function reads the previous score and creates a new object with the score increased by one. The name is preserved. This approach is useful when updates depend on the latest queued state.
10. Updating Objects Using Form Inputs
React forms often store multiple input values in a single object. When a user types into an input, the corresponding object property can be updated using the spread operator.
Example:
import { useState } from "react";
function RegistrationForm() {
const [form, setForm] = useState({
name: "",
email: "",
city: ""
});
function handleChange(event) {
const { name, value } = event.target;
setForm(previousForm => ({
...previousForm,
[name]: value
}));
}
return (
<div>
<h2>Registration Form</h2>
<input
name="name"
placeholder="Enter your name"
value={form.name}
onChange={handleChange}
/>
<input
name="email"
placeholder="Enter your email"
value={form.email}
onChange={handleChange}
/>
<input
name="city"
placeholder="Enter your city"
value={form.city}
onChange={handleChange}
/>
<h3>Form Details</h3>
<p>Name: {form.name}</p>
<p>Email: {form.email}</p>
<p>City: {form.city}</p>
</div>
);
}
export default RegistrationForm;
Explanation:
- The
form object stores all three input values.
- The
handleChange() function runs whenever an input changes.
event.target.name identifies the property to update.
event.target.value contains the latest input value.
[name]: value dynamically updates the correct property.
- The spread operator preserves the other form values.
11. Understanding Computed Property Names
Computed property names allow you to use an expression as an object property name. In form handling, this technique makes one event handler reusable for several input fields.
Example:
const fieldName = "email";
const fieldValue = "[email protected]";
const updatedUser = {
...user,
[fieldName]: fieldValue
};
Here, the email property receives the new value. The square brackets allow JavaScript to evaluate the variable and use its value as the property name.
12. Updating Nested Objects in State
An object may contain another object as one of its properties. Such structures are commonly called nested objects. When updating a nested property, you must create new copies of the objects along the path to that property.
Example State:
const [user, setUser] = useState({
name: "Rahul",
address: {
city: "Mumbai",
country: "India"
}
});
Correct Way to Update a Nested Property:
function updateCity() {
setUser(previousUser => ({
...previousUser,
address: {
...previousUser.address,
city: "Pune"
}
}));
}
Explanation: The first spread copies the existing user properties. The second spread copies the existing address properties. The city is then changed to Pune without losing the country value or the user's name.
Important: The spread operator makes a shallow copy. Copying only the outer object does not create independent copies of its nested objects. Therefore, copy each level that needs to change.
13. Updating an Object with Conditional Logic
You can use conditions to decide which property should be updated. This is useful when application behavior depends on the current state or a user action.
Example:
function updateStatus() {
setUser(previousUser => ({
...previousUser,
active: !previousUser.active
}));
}
This example toggles the active property between true and false. The previous user properties are preserved.
14. Common Mistakes When Updating Objects
| Mistake |
Problem |
Correct Approach |
| Directly changing a property |
Mutates existing state. |
Create a new object. |
| Calling the setter with the same object |
React may skip the update because the reference is unchanged. |
Pass a new object reference. |
| Forgetting the spread operator |
Other properties may be lost. |
Copy previous properties with .... |
| Updating a nested property directly |
Mutates a nested object in state. |
Copy each affected level. |
| Using stale state for dependent updates |
Queued updates may use an outdated value. |
Use an updater function when appropriate. |
| Confusing assignment with object creation |
Changing a variable or property does not automatically produce a new state object. |
Return a newly created object to the setter. |
15. Updating Objects vs. Mutating Objects
| Updating Correctly |
Mutating Incorrectly |
| Creates a new object. |
Changes an existing object. |
| Uses the state setter. |
May modify state without using the setter. |
| Preserves previous state snapshots. |
Can alter data referenced by previous renders. |
| Works well with React's state model. |
Can cause unexpected rendering behavior. |
| Often uses the spread operator. |
Often uses direct property assignment. |
16. Practical Project: User Profile Updater
Objective: Create a React component that allows users to update their name, age, and city. The component should preserve all other values whenever a single property changes.
Complete Code:
import { useState } from "react";
function UserProfileUpdater() {
const [user, setUser] = useState({
name: "Manish",
age: 25,
city: "Mumbai"
});
function handleChange(event) {
const { name, value } = event.target;
setUser(previousUser => ({
...previousUser,
[name]: name === "age" ? Number(value) : value
}));
}
return (
<div>
<h2>User Profile Updater</h2>
<label>Name: </label>
<input
name="name"
value={user.name}
onChange={handleChange}
/>
<br />
<label>Age: </label>
<input
type="number"
name="age"
value={user.age}
onChange={handleChange}
/>
<br />
<label>City: </label>
<input
name="city"
value={user.city}
onChange={handleChange}
/>
<h3>Updated Profile</h3>
<p>Name: {user.name}</p>
<p>Age: {user.age}</p>
<p>City: {user.city}</p>
</div>
);
}
export default UserProfileUpdater;
Project Explanation:
- The
useState() Hook initializes the user object.
- Three input fields allow the user to edit their profile.
- The
handleChange() function identifies the field being edited.
- The updater function copies the previous object and replaces the changed property.
- The age is converted to a number because HTML input values are normally strings.
- React renders the updated profile values.
17. Best Practices for Updating Objects in State
- Always treat objects stored in React state as read-only.
- Use the setter returned by
useState() to request updates.
- Use the spread operator to preserve existing properties when updating only part of an object.
- Use functional state updates when the next state depends on the previous state.
- Copy nested objects at every level that needs to change.
- Keep state structures as simple and manageable as possible.
- Use descriptive property names and reusable event handlers.
- Remember that object spread performs a shallow copy, not a deep clone.
- Test that updating one property does not accidentally remove other properties.
18. Interview Questions and Answers
Q1. What does updating objects in state mean in React?
Answer: It means creating a new version of an object with updated property values and passing it to the state setter so React can process the state update.
Q2. Why should we not mutate objects in React state?
Answer: Direct mutation changes existing state data without properly notifying React through a new state value. It can cause skipped updates and unexpected behavior.
Q3. What is the spread operator?
Answer: The object spread syntax (...) copies enumerable properties into a new object. It is commonly used to preserve existing properties while updating selected values.
Q4. How do you update one property of an object?
Answer: Use the state setter with the spread operator, such as setUser({ ...user, name: "Amit" }). For updates that depend on previous state, an updater function is often preferable.
Q5. How do you update a nested object?
Answer: Create new copies of the outer object and each nested object along the path to the property being changed.
Q6. What is the difference between mutation and immutability?
Answer: Mutation changes an existing object, whereas an immutable update creates a new object while preserving the original object.
Q7. Can we update multiple properties at once?
Answer: Yes. Specify multiple properties in the new object passed to the state setter.
Q8. What is the purpose of a functional state update?
Answer: It calculates the next state from the previous state supplied by React, making it useful when updates depend on previous values.
Q9. Does the spread operator perform a deep copy?
Answer: No. It performs a shallow copy. Nested objects remain shared references unless they are copied separately.
Q10. Where are object state updates used in real projects?
Answer: They are used in registration forms, profile editors, dashboards, shopping carts, settings pages, and other interactive interfaces.
19. Practice Exercises
- Create a student object with name, age, and course properties. Add a button that updates the course.
- Create a user profile form with name, email, and city inputs.
- Update two properties of an object when a button is clicked.
- Create a nested address object and update its city without changing its country.
- Create a task object with a completed property and toggle its value.
- Build a product editor that updates the product name and price.
- Rewrite an incorrect state mutation example using the spread operator.
20. Quick Revision Checklist
- Understand JavaScript objects and key-value pairs.
- Understand state and the
useState() Hook.
- Avoid directly mutating objects stored in state.
- Use the spread operator to create updated objects.
- Preserve properties that do not need to change.
- Use updater functions for state-dependent calculations.
- Update nested objects by copying each affected level.
- Handle multiple form fields using computed property names.
- Remember that the spread operator creates only a shallow copy.
- Practice building a complete user profile updater.
21. Conclusion
Updating objects in state is an essential React JS skill. It allows developers to manage form data, user profiles, application settings, and other structured information reliably. The key principle is to avoid mutating existing state objects and instead create a new object with the required changes.
By using the spread operator, functional state updates, and correct nested-object copying, you can build React applications that are easier to understand, maintain, and debug.
22. React JS Training and Course Demo
Learn more about React JS concepts, component development, state management, and practical application development through JustAcademy.
Course Link: JustAcademy React JS Training
Demo Registration: Register for React JS Course Demo