Why Object References Matter in React State :👈 👉:TypeScript Props for React Components

Shallow Copy vs Deep Copy in React State

Shallow Copy vs Deep Copy in React State

1. Introduction

In React, state can contain primitive values, objects, arrays, or nested objects.

When updating object or array state, it is important to understand the difference between Shallow Copy and Deep Copy.

React recommends updating state immutably instead of modifying existing objects or arrays directly.

2. What Is a Shallow Copy?

A shallow copy creates a new outer object, but nested objects and arrays are still shared by reference.

  • The outer object is copied.
  • Nested objects are not copied.
  • Changes to a shared nested object can affect both the original and copied objects.

Example

const user = {
    name: "John",
    address: {
        city: "Hyderabad",
        country: "India"
    }
};
// Shallow copy
const copiedUser = { ...user };
console.log(user === copiedUser); // false
console.log(user.address === copiedUser.address);
// true

Here:

  • user and copiedUser are different objects.
  • Both objects refer to the same address object.

Demonstrating the problem

copiedUser.address.city = "Bangalore";
console.log(user.address.city);
// Bangalore
console.log(copiedUser.address.city);
// Bangalore

Why did the original object change?

Because the nested address object was not copied. Both objects point to the same nested object.

3. What Is a Deep Copy?

A deep copy creates a new object and also copies its nested objects and arrays.

The original and copied objects do not share references for the copied nested data.

Example using structuredClone()

const user = {
    name: "John",
    address: {
        city: "Hyderabad",
        country: "India"
    }
};
// Deep copy
const copiedUser = structuredClone(user);
console.log(user === copiedUser); // false
console.log(user.address === copiedUser.address);
// false

Demonstrating the result

copiedUser.address.city = "Bangalore";
console.log(user.address.city);
// Hyderabad
console.log(copiedUser.address.city);
// Bangalore

Why did the original object remain unchanged?

Because structuredClone() created separate copies of the nested objects as well.

Note: structuredClone() supports many common data types, but it cannot clone every JavaScript value, such as functions and DOM nodes.

4. Shallow Copy vs Deep Copy

Feature Shallow Copy Deep Copy
Outer object New object New object
Nested objects Shared references Independently copied
Copy depth One level Nested levels
Performance Usually faster Can be more expensive
Memory usage Usually lower Usually higher
Nested mutation Can affect original Does not affect original copied data
Common methods Spread, Object.assign() structuredClone()

5. Shallow Copy in React State

React state should be updated immutably.

A shallow copy is often sufficient when the state contains only primitive properties or when you explicitly copy every level that you modify.

Incorrect approach: Direct mutation

import { useState } from "react";
function UserProfile() {
    const [user, setUser] = useState({
        name: "John",
        address: {
            city: "Hyderabad"
        }
    });
    const updateCity = () => {
        user.address.city = "Bangalore";
        setUser(user);
    };
    return (
        <div>
            <p>{user.address.city}</p>
            <button onClick={updateCity}>
                Update City
            </button>
        </div>
    );
}

Problem:

  • The existing state object is modified directly.
  • The same object reference is passed to setUser.
  • React may skip the update because the new state is identical to the previous state according to Object.is.

Correct approach: Shallow copy at every modified level

import { useState } from "react";
function UserProfile() {
    const [user, setUser] = useState({
        name: "John",
        address: {
            city: "Hyderabad"
        }
    });
    const updateCity = () => {
        setUser(prevUser => ({
            ...prevUser,
            address: {
                ...prevUser.address,
                city: "Bangalore"
            }
        }));
    };
    return (
        <div>
            <p>{user.address.city}</p>
            <button onClick={updateCity}>
                Update City
            </button>
        </div>
    );
}

Why does this work?

  1. ...prevUser creates a new outer object.
  2. ...prevUser.address creates a new address object.
  3. city receives the updated value.
  4. The original state objects remain unchanged.

This is the recommended approach for ordinary nested React state updates.

6. Does React Require Deep Copy Every Time?

No. React does not require a deep copy for every state update.

You only need to create new objects along the path of the properties you are changing.

Consider this state:

const [user, setUser] = useState({
    name: "John",
    address: {
        city: "Hyderabad"
    },
    preferences: {
        theme: "dark"
    }
});

Suppose you only want to update the city.

setUser(prev => ({
    ...prev,
    address: {
        ...prev.address,
        city: "Bangalore"
    }
}));

The preferences object can safely retain its existing reference because it is not being modified.

This approach is efficient and follows React's immutable state update principle.

7. Deep Copy in React State

Sometimes you need a completely independent copy of an object, including its nested data.

You can use structuredClone() when the state contains supported structured-cloneable values.

Example

const [user, setUser] = useState({
    name: "John",
    address: {
        city: "Hyderabad"
    }
});
const updateUser = () => {
    const copiedUser = structuredClone(user);
    copiedUser.address.city = "Bangalore";
    setUser(copiedUser);
};

Here, the entire object is copied before making changes.

However, for a simple state update, copying the entire object may be unnecessary.

Important: For updates based on the previous state, prefer the functional updater form:

setUser(prevUser => {
    const copiedUser = structuredClone(prevUser);
    copiedUser.address.city = "Bangalore";
    return copiedUser;
});

This ensures the update is based on the latest state value.

8. Common Ways to Copy Objects in JavaScript

1. Spread Operator

Creates a shallow copy.

const copied = { ...original };

2. Object.assign()

Also creates a shallow copy.

const copied = Object.assign({}, original);

3. Array Spread

Creates a shallow copy of an array.

const copiedArray = [...originalArray];

4. structuredClone()

Creates a deep copy for supported values.

const copied = structuredClone(original);

5. JSON.parse() and JSON.stringify()

An older workaround for simple JSON-compatible data.

const copied = JSON.parse(JSON.stringify(original));

Limitations:

  • Does not preserve functions.
  • Does not preserve undefined object properties.
  • Does not preserve Date objects as Date objects.
  • Does not support circular references.
  • Does not preserve several other JavaScript data types.

Prefer structuredClone() when its supported data types meet your needs.

9. Using Immer for Complex React State

When state contains deeply nested objects, manually copying every modified level can become difficult.

The Immer library makes immutable updates easier.

Example

import { useImmer } from "use-immer";
function UserProfile() {
    const [user, updateUser] = useImmer({
        name: "John",
        address: {
            city: "Hyderabad"
        }
    });
    const updateCity = () => {
        updateUser(draft => {
            draft.address.city = "Bangalore";
        });
    };
    return (
        <div>
            <p>{user.address.city}</p>
            <button onClick={updateCity}>
                Update City
            </button>
        </div>
    );
}

Immer creates the necessary immutable updates behind the scenes.

Although the code looks like direct mutation, Immer uses a draft mechanism to produce a new immutable state.

10. When Should You Use Shallow Copy or Deep Copy?

Use Shallow Copy When:

  • Updating normal React state objects.
  • Updating a specific nested property.
  • Updating arrays using map(), filter(), or spread syntax.
  • You want to preserve references to unchanged nested objects.
  • You want efficient immutable updates.

Use Deep Copy When:

  • You need a completely independent copy of supported nested data.
  • You need to create a separate editable version of an object.
  • You need to prevent changes in one copy from affecting another.
  • You are working with complex data where independent nested references are required.

Do not use deep copying automatically for every React state update. It can create unnecessary objects and consume additional memory.

11. Common Mistakes

  1. Thinking spread syntax creates a deep copy: Spread syntax only copies one level.
  2. Updating nested objects directly: This can mutate existing state.
  3. Deep-copying the entire state unnecessarily: Copy only the levels that need to change.
  4. Using JSON serialization for every object: It has important data-type limitations.
  5. Assuming a new outer reference means all nested references are new: Nested objects may still be shared.
  6. Ignoring functional state updates: Use setState(prev => ...) when the next value depends on previous state.

12. Interview Questions and Answers

Q1. What is a shallow copy?

A shallow copy creates a new outer object but retains references to nested objects and arrays.

Q2. What is a deep copy?

A deep copy creates an independent copy of an object, including its nested objects and arrays.

Q3. Is the JavaScript spread operator a deep copy?

No. The spread operator creates a shallow copy.

Q4. Why is shallow copying commonly used in React?

It allows React developers to create new object references efficiently while preserving unchanged nested references.

Q5. Why should we avoid directly mutating React state?

Direct mutation can preserve the same object reference, making it difficult for React to detect changes correctly. It also makes state updates unpredictable.

Q6. How do you update a nested object without mutating state?

Use the spread operator at every level that needs to change.

Q7. What is structuredClone()?

It is a built-in JavaScript method that creates a deep copy of supported structured-cloneable values.

Q8. Does React require deep copying of state?

No. React requires immutable updates. A shallow copy of each modified level is generally sufficient.

Q9. What is Immer?

Immer is a library that simplifies immutable updates by allowing developers to write update logic using a draft object.

Q10. What happens if you shallow-copy an object and modify a nested property?

The original object can also be affected because both objects share the same nested reference.

13. Key Takeaways

  • Shallow copy creates a new outer object but shares nested references.
  • Deep copy creates independent copies of nested data.
  • Spread syntax and Object.assign() create shallow copies.
  • structuredClone() can create deep copies of supported values.
  • React state should be updated immutably.
  • For nested React state updates, copy every level that you modify.
  • Deep copying the entire state is not necessary for ordinary updates.
  • Immer can simplify complex immutable state updates.

Remember: In React, the goal is not to deep-copy everything. The goal is to create new references for the objects you update while leaving the original state unchanged.

🔙
Why Object References Matter in React State :👈 👉:TypeScript Props for React Components

Comments and Discussion