Course contentsShow
← React
Lesson 1208 of 2,39631. Forms in ReactFree lesson

Updating Nested Form State Immutably

Techniques for updating deeply nested properties without mutating state: spread operators, immer integration.

Updating Nested Form State Immutably

What you'll learn: How to safely update deeply nested form properties without mutating state, using spread operators and tools like Immer.

When your form state contains nested objects or arrays, updating a deep property requires careful immutable techniques. You can't just reach in and modify—you must recreate the path from the root to the changed property.

The Spread Operator Approach

The manual way uses the spread operator (...) at each nesting level:

const [formData, setFormData] = useState({
  user: {
    profile: {
      address: {
        city: '',
        zip: ''
      }
    }
  }
});

// Update city deeply nested inside
const handleCityChange = (newCity) => {
  setFormData({
    ...formData,
    user: {
      ...formData.user,
      profile: {
        ...formData.user.profile,
        address: {
          ...formData.user.profile.address,
          city: newCity
        }
      }
    }
  });
};

This works but becomes verbose and error-prone with deep nesting. You're essentially rebuilding each layer of the structure.

Immer Integration

Immer lets you write "mutative" code that's automatically converted to immutable updates:

import { produce } from 'immer';

const handleCityChange = (newCity) => {
  setFormData(produce(draft => {
    draft.user.profile.address.city = newCity;
  }));
};

The draft is a proxy object—changes to it generate a new immutable state behind the scenes. This reads like simple assignment but maintains immutability.

Think of Immer like a recording studio: you work on a "draft" copy, making changes freely, and when you're done, it produces a final immutable "master" recording without affecting the original.

Key Takeaway: For nested form state, use spread operators for shallow updates or Immer's produce for deep updates—both avoid mutation while keeping React's state transitions predictable.