| JavaScript Event Loop Behavior in React :👈 | 👉:Shallow Copy vs Deep Copy in React State |
Why Object References Matter in React State |
Why Object References Matter in React State
1. Introduction
Understanding object references is very important when working with React state, especially when using objects and arrays.
React uses state updates to determine when a component needs to render again. When working with objects and arrays, React compares the new state with the previous state using identity comparison (similar to Object.is()).
If you modify an existing object directly and pass the same object reference back to React, React may skip the update because the reference has not changed.
Understanding object references helps prevent:
- UI not updating after a state change.
- Unexpected changes in multiple components.
- Incorrect state updates.
- Problems with React.memo and useMemo.
- Unnecessary component rendering.
- Stale or inconsistent data.
2. What Is an Object Reference in JavaScript?
In JavaScript, objects and arrays are reference types.
When you assign an object to another variable, JavaScript copies the reference, not the entire object.
Example
const user1 = {
name: "John",
age: 25
};
const user2 = user1;
user2.name = "David";
console.log(user1.name);
console.log(user2.name);
Output:
David
David
Why?
Both variables point to the same object in memory. Changing the object through one reference is visible through the other reference.
3. Primitive Values vs Object References
JavaScript handles primitive values and objects differently during assignment.
| Primitive Values | Objects and Arrays |
|---|---|
| Store the value directly. | Variables hold references to objects. |
| Assignment copies the value. | Assignment copies the reference. |
| Changing one variable does not change another. | Changing an object through one reference affects other references to that object. |
| Examples: number, string, boolean. | Examples: object, array, function. |
Primitive Example
let a = 10;
let b = a;
b = 20;
console.log(a); // 10
console.log(b); // 20
Object Example
const a = { name: "John" };
const b = a;
b.name = "David";
console.log(a.name); // David
console.log(b.name); // David
4. Why Object References Matter in React State
React uses state to manage component data. When state changes, React determines whether an update is necessary.
For state values, React compares the previous and next values using Object.is(). If they are equal, React can skip rendering work for that update.
For objects and arrays, this means reference identity matters.
Incorrect Example: Mutating State Directly
import { useState } from "react";
function UserProfile() {
const [user, setUser] = useState({
name: "John",
age: 25
});
function updateName() {
user.name = "David";
setUser(user);
}
return (
<div>
<h2>{user.name}</h2>
<button onClick={updateName}>
Update Name
</button>
</div>
);
}
export default UserProfile;
Problem:
- The existing object is modified directly.
- The reference remains the same.
setUser(user)receives the same object reference.- React may skip the update because the old and new state are identical according to
Object.is().
This is why directly modifying React state is not recommended.
Correct Example: Create a New Object
import { useState } from "react";
function UserProfile() {
const [user, setUser] = useState({
name: "John",
age: 25
});
function updateName() {
setUser({
...user,
name: "David"
});
}
return (
<div>
<h2>{user.name}</h2>
<button onClick={updateName}>
Update Name
</button>
</div>
);
}
export default UserProfile;
Why does this work?
- The spread operator creates a new object.
- The new object has a different reference.
- The existing properties are copied into the new object.
- The
nameproperty is updated. - React detects a different state value and schedules an update.
5. Understanding the Spread Operator (...)
The spread operator is commonly used to create new objects and arrays without directly modifying the existing state.
Object Example
const user = {
name: "John",
age: 25
};
const updatedUser = {
...user,
age: 26
};
console.log(user.age); // 25
console.log(updatedUser.age); // 26
The original object remains unchanged, and a new object is created.
Array Example
const users = ["John", "David"];
const updatedUsers = [...users, "Michael"];
console.log(users);
// ["John", "David"]
console.log(updatedUsers);
// ["John", "David", "Michael"]
6. Shallow Copy vs Deep Copy
An important point is that the spread operator creates a shallow copy, not a deep copy.
Shallow Copy
A shallow copy creates a new outer object, but nested objects are still shared references.
const user = {
name: "John",
address: {
city: "Hyderabad"
}
};
const updatedUser = {
...user
};
console.log(user === updatedUser); // false
console.log(
user.address === updatedUser.address
); // true
The outer objects are different, but both contain a reference to the same nested address object.
Correctly Updating a Nested Object
When updating a nested property, create new objects along the entire path to the property being changed.
const updatedUser = {
...user,
address: {
...user.address,
city: "Bangalore"
}
};
Now both the outer user object and nested address object have new references.
7. Updating Nested Objects in React
Consider a React component that stores user information with a nested address object.
Complete Example
import { useState } from "react";
function UserProfile() {
const [user, setUser] = useState({
name: "John",
age: 25,
address: {
city: "Hyderabad",
country: "India"
}
});
function updateCity() {
setUser({
...user,
address: {
...user.address,
city: "Bangalore"
}
});
}
return (
<div>
<h2>{user.name}</h2>
<p>Age: {user.age}</p>
<p>City: {user.address.city}</p>
<button onClick={updateCity}>
Update City
</button>
</div>
);
}
export default UserProfile;
Explanation:
...usercreates a new outer object....user.addresscreates a new nested address object.- The city property is changed in the new address object.
- React receives a new state reference.
- React schedules the component update.
8. Why Object References Matter with React.memo
React.memo is used to avoid unnecessary re-rendering of a component when its props have not changed according to its comparison.
For object props, React.memo's default comparison checks whether the object references are the same.
Example
import React from "react";
const UserDetails = React.memo(function UserDetails({ user }) {
console.log("UserDetails rendered");
return <h2>{user.name}</h2>;
});
export default UserDetails;
Consider the parent component:
function Parent() {
const user = {
name: "John"
};
return <UserDetails user={user} />;
}
Every time the parent renders, it creates a new object. The reference changes, even if the object contains the same values.
Therefore, React.memo may render UserDetails again.
Better Approach Using useMemo
import React, { useMemo, useState } from "react";
function Parent() {
const [count, setCount] = useState(0);
const user = useMemo(() => {
return {
name: "John"
};
}, []);
return (
<div>
<button onClick={() => setCount(count + 1)}>
Count: {count}
</button>
<UserDetails user={user} />
</div>
);
}
In this example, useMemo caches the object reference between renders while its dependencies remain unchanged.
Important: Do not use useMemo for every object. Use it when profiling shows that stabilizing a reference provides a meaningful performance benefit.
9. Why Object References Matter with useEffect
React compares effect dependencies using Object.is(). If an object is created again during every render, its reference changes, so an effect depending on it can run again.
Problem Example
import { useEffect, useState } from "react";
function Example() {
const [count, setCount] = useState(0);
const options = {
page: 1
};
useEffect(() => {
console.log("Effect executed");
}, [options]);
return (
<button onClick={() => setCount(count + 1)}>
Count: {count}
</button>
);
}
Whenever the component renders, a new options object is created. Its reference changes, causing the effect to run again.
Better Approach: Move the Object Inside the Effect
useEffect(() => {
const options = {
page: 1
};
console.log("Effect executed", options);
}, []);
Now the object is created inside the effect instead of being recreated as a dependency on every render.
When an object genuinely needs to be shared across renders, consider useMemo with the correct dependencies.
10. Functional State Updates and Object References
When the next state depends on the previous state, use the functional update form of the state setter.
Example
const [user, setUser] = useState({
name: "John",
age: 25
});
function updateAge() {
setUser(previousUser => ({
...previousUser,
age: previousUser.age + 1
}));
}
Why use this approach?
- It receives the latest pending state value.
- It avoids relying on a potentially outdated state variable captured by a closure.
- It creates a new object reference.
- It preserves the other object properties.
11. Updating Arrays in React State
Arrays are also reference types. Therefore, avoid modifying state arrays directly using methods such as push(), pop(), or splice().
Incorrect Example
const [users, setUsers] = useState([
"John",
"David"
]);
function addUser() {
users.push("Michael");
setUsers(users);
}
This modifies the existing array and passes the same reference back to React.
Correct Example
function addUser() {
setUsers(previousUsers => [
...previousUsers,
"Michael"
]);
}
Other common immutable array operations:
| Operation | Recommended approach |
|---|---|
| Add an item | [...items, newItem] |
| Remove an item | items.filter() |
| Update an item | items.map() |
| Sort without mutation | [...items].sort() |
| Replace an item | items.map() |
12. Common Mistakes
Mistake 1: Directly Mutating an Object
user.name = "David";
setUser(user);
Problem: The same object reference is passed back to React.
Correct:
setUser({
...user,
name: "David"
});
Mistake 2: Assuming Spread Creates a Deep Copy
const updatedUser = {
...user
};
Problem: Nested objects remain shared references.
Correct:
const updatedUser = {
...user,
address: {
...user.address,
city: "Bangalore"
}
};
Mistake 3: Creating New Objects Unnecessarily
const user = {
name: "John"
};
const updatedUser = {
...user
};
Even though the values are identical, the references are different. This can cause unnecessary updates when the object is passed as a prop or used as an effect dependency.
Mistake 4: Using JSON.stringify() for Reference Comparison
if (JSON.stringify(user1) === JSON.stringify(user2)) {
console.log("Same");
}
Problem: JSON serialization is not a general-purpose object equality solution. It can be inefficient and does not correctly handle every JavaScript value.
Use reference comparison when identity is what matters, or an appropriate deep-equality approach when value comparison is required.
13. Best Practices
- Never directly mutate objects or arrays stored in React state.
- Create new object references when updating state.
- Use the spread operator for shallow immutable updates.
- When updating nested objects, create new objects along the entire path.
- Use functional state updates when the next value depends on the previous value.
- Understand that spread syntax creates shallow copies, not deep copies.
- Use
React.memo,useMemo, anduseCallbackonly when they provide a measurable benefit. - Be careful when using objects and arrays as
useEffectdependencies. - Use immutable array methods such as
map(),filter(), andslice(). - For complex nested state, consider a state management approach or an immutable update library such as Immer.
14. Interview Questions and Answers
Q1. What is an object reference in JavaScript?
An object reference is a value that identifies an object. When an object is assigned to another variable, the reference is copied rather than creating an independent copy of the object.
Q2. Why are object references important in React?
React uses identity comparison to determine whether state values and dependencies have changed. For objects and arrays, reference identity matters. A new reference helps React detect an immutable state update.
Q3. Why should we not mutate React state directly?
Direct mutation changes the existing object without creating a new reference. React may not detect the update because the previous and next state references are identical.
Q4. What is the difference between shallow copy and deep copy?
A shallow copy creates a new outer object but retains references to nested objects. A deep copy creates independent copies of nested data as well.
Q5. What does the spread operator do?
The spread operator expands the properties of an object or elements of an array. It is commonly used to create new objects and arrays for immutable state updates.
Q6. Why does React.memo sometimes fail to prevent re-rendering?
If a parent creates a new object or function during every render, the prop reference changes. React.memo's default comparison treats the prop as changed, even when its contents are identical.
Q7. How do object references affect useEffect?
React compares effect dependencies using Object.is(). If an object is recreated during every render, its reference changes and the effect may run again.
Q8. What is the difference between Object.is() and deep equality?
Object.is() compares object identity, not the contents of two separate objects. Deep equality checks whether nested values are equivalent.
Q9. How do you update a nested object in React state?
Create a new outer object and new objects along the nested property path using the spread operator. This preserves immutability and creates new references where required.
Q10. Why should we use functional state updates?
Functional state updates receive the previous pending state and are useful when the next state depends on the previous state. They also help avoid stale state values captured by closures.
15. Final Summary
- Object Reference: Identifies an object in memory.
- Primitive Assignment: Copies the primitive value.
- Object Assignment: Copies the object reference.
- React State: Uses identity comparison to determine whether a state value changed.
- Immutable Update: Creates a new object or array instead of modifying existing state.
- Spread Operator: Creates shallow copies of objects and arrays.
- Nested Updates: Require new references along the updated property path.
- React.memo: Uses prop comparison to decide whether a memoized component can skip rendering.
- useEffect: Compares dependencies using
Object.is(). - Functional Updates: Use the previous state to calculate the next state safely.
Remember: In React, do not modify an existing state object or array directly. Create a new reference when updating state. This makes state changes predictable and helps React identify updates correctly.
| JavaScript Event Loop Behavior in React :👈 | 👉:Shallow Copy vs Deep Copy in React State |
Comments and Discussion