Skip to main content

Welcome to a Grasp lesson

Create a free account to keep studying and create your own study path.

Lesson 23

Immutable State Updates for Objects and Arrays

Recommended resources

Introduction

Hello! In our last lesson, we distinguished between using multiple useState hooks for unrelated state and grouping related data into a single state object. We concluded with a crucial rule: when state is an object or array, you must treat it as immutable. This means you can't modify it directly. Instead, you must create a new object or array for every update.

Today, we'll do the promised deep dive into this principle. The goal of this lesson is to master the techniques for working with object and array state, ensuring immutable updates. We will cover the common patterns for adding, updating, and removing items from these complex data structures without ever mutating them directly.

Understanding this is not just about following a rule; it's fundamental to how React works. React determines whether to re-render a component by checking if its state has changed. For objects and arrays, it does this by comparing their references in memory (i.e., oldState === newState). If you modify an array directly (e.g., using array.push()), its reference in memory doesn't change, so React won't "see" the update and your UI won't refresh. By always creating a new array or object, you guarantee React detects the change.


The Immutable Update Patterns

The official React documentation provides an excellent, comprehensive guide to these patterns. It covers everything from adding and removing items to updating nested objects within arrays.

Updating Arrays in State

To start, please read the official React guide 'Updating Arrays in State'. This is a foundational text that we will build upon throughout the lesson. It details the core patterns for immutable array manipulation.

Read the article from the beginning down to (but not including) the section 'Write concise update logic with Immer'. Pay close attention to the table comparing mutating vs. non-mutating methods and the specific code examples for adding, removing, replacing, and transforming items.

That was a lot of information, but it covers almost every scenario you'll encounter. Let's break down and reinforce the most critical patterns with more examples. For this section, you might also find it helpful to see these patterns implemented in a live-coding format.

React State Array of Objects

The following video by Sam Meech-Ward demonstrates these concepts in a practical example, building a 'jokes' application. It's a great visual complement to the text you just read.

You can watch the entire video (about 19 minutes) as we'll refer to different parts. As you watch, notice how each state update involves creating a new array using methods like spread (...), filter, or map, and then calling the state setter function with that new array.

Let's synthesize what we've learned from these resources.

1. Adding Items to an Array

To add an item, create a new array and use the JavaScript spread syntax (...) to copy the existing items, then add your new item.

interface Todo {
  id: number;
  text: string;
  completed: boolean;
}

const [todos, setTodos] = useState<Todo[]>([
  { id: 1, text: 'Learn React', completed: true },
]);

const handleAddTodo = (text: string) => {
  const newTodo: Todo = {
    id: Date.now(), // Using timestamp for a unique ID
    text: text,
    completed: false,
  };

  // Add to the end of the array
  setTodos(prevTodos => [...prevTodos, newTodo]);
  
  // Or, to add to the beginning:
  // setTodos(prevTodos => [newTodo, ...prevTodos]);
};

This is demonstrated in the react.dev article section "Adding to an array" and in the video from 02:42.

2. Removing Items from an Array

To remove an item, use the filter method. It returns a new array containing only the elements that pass the test, perfectly aligning with the principle of immutability.

const handleRemoveTodo = (idToRemove: number) => {
  setTodos(prevTodos => prevTodos.filter(todo => todo.id !== idToRemove));
};

This is covered in the react.dev section "Removing from an array" and in the video from 05:12.

3. Updating an Object in an Array

This is the most complex but also one of the most common operations. You need to combine map to create a new array with the spread syntax to create a new object for the item you're updating.

The map method iterates over each item. For the item you want to change, you return a new object with the copied properties of the old object plus your changes. For all other items, you return them untouched.

const handleToggleTodo = (idToToggle: number) => {
  setTodos(prevTodos => 
    prevTodos.map(todo => {
      // If this is not the todo we're looking for, return it as-is
      if (todo.id !== idToToggle) {
        return todo;
      }
      
      // Otherwise, create a new object with the toggled 'completed' status
      return { ...todo, completed: !todo.completed };
    })
  );
};

This pattern is critical. It ensures that you create a new array and a new object for the item that changed, propagating the change correctly. The react.dev article has a fantastic section titled "Updating objects inside arrays" that explains this, including a buggy example that shows what happens if you mutate state directly. The video also covers this exact pattern starting at 12:00.

Test your understanding!

You have a state variable for a list of products in a shopping cart:

interface CartItem {
  id: number;
  name: string;
  quantity: number;
}

const [cart, setCart] = useState<CartItem[]>([
  { id: 1, name: 'Laptop', quantity: 1 },
  { id: 2, name: 'Mouse', quantity: 1 },
]);

Write the handleIncrementQuantity function that takes a product id and increases its quantity by one, following immutable update patterns.

Show answer

You should use the map method to iterate over the array. When you find the matching item, return a new object with the incremented quantity.

const handleIncrementQuantity = (idToIncrement: number) => {
  setCart(prevCart => 
    prevCart.map(item => 
      item.id === idToIncrement 
        ? { ...item, quantity: item.quantity + 1 }
        : item
    )
  );
};

4. Updating Nested Objects

The same principle of spreading at each level applies to plain objects as well. If you need to update a property in a nested object, you must create a new copy of the nested object and a new copy of the parent object.

interface UserProfile {
  id: number;
  name: string;
  contact: {
    email: string;
    phone: string;
  };
}

const [user, setUser] = useState<UserProfile>({
  id: 1,
  name: 'John Doe',
  contact: {
    email: 'john.doe@example.com',
    phone: '123-456-7890',
  },
});

const handleUpdateEmail = (newEmail: string) => {
  setUser(prevUser => ({
    ...prevUser, // 1. Copy the top-level properties
    contact: {
      ...prevUser.contact, // 2. Copy the nested object's properties
      email: newEmail, // 3. Overwrite the specific nested property
    },
  }));
};

The article "Master React useState: Patterns That Scale" explains this pattern very clearly.

Master React useState: Patterns That Scale

For a clear explanation on updating nested objects, please review this section from the Strapi blog.

Read the section 'Objects: Updating Nested Properties Safely'. Note the example code for both top-level and nested updates.


Modern JavaScript for Simpler Immutable Updates

The patterns using map, filter, and spread are the established standard. However, your strong JavaScript background makes you a perfect candidate to learn about newer JS features that make this even cleaner.

ES2023 introduced new array methods specifically designed for immutable operations:

  • toSorted(): The immutable version of sort().
  • toReversed(): The immutable version of reverse().
  • toSpliced(): The immutable version of splice().
  • with(index, value): Returns a new array with the element at index replaced by value.

These methods are tailor-made for React state updates because they always return a new array.

6 NEW ES2023 Array Methods with React + TypeScript Examples

The following video from Coding Garden provides an excellent overview of these new methods, showing practical examples in a React + TypeScript context.

Watch from 03:10 to 07:10. The presenter shows how toSpliced can replace filter for removing an item by index, and how with can simplify replacing an item compared to map.

Let's rewrite our handleToggleTodo function using the with() method. It's not necessarily "better" than map in all cases, but it can be more direct when you know the index of the item you want to replace.

const handleToggleTodoWithIndex = (indexToToggle: number) => {
  setTodos(prevTodos => {
    const todoToUpdate = prevTodos[indexToToggle];
    const updatedTodo = { ...todoToUpdate, completed: !todoToUpdate.completed };
    
    // Replace the item at the specific index with the updated one
    return prevTodos.with(indexToToggle, updatedTodo);
  });
};

As the video notes, browser and TypeScript support for these methods is still evolving. You may need polyfills (like core-js) or custom type definitions for now, but they are the future of immutable array handling in JavaScript.


Conclusion

Mastering immutable state updates is a significant step towards writing robust and predictable React applications. You've moved beyond simply using state to understanding how to manage complex data structures correctly.

Key Takeaways:

  • Never Mutate State: React relies on reference equality to detect changes. Mutating state directly will lead to missed re-renders and bugs.
  • Create New Copies: Always create new arrays and objects for every update and pass them to your state setter function.
  • Use Standard JS Patterns:
    • Add: Array spread syntax ([...arr, newItem]).
    • Remove: arr.filter(...).
    • Update/Transform: arr.map(...).
  • Update Nested Data Carefully: When updating nested objects or objects within arrays, you must create new copies at every level of the structure you are changing.
  • Embrace Modern JS: Keep an eye on new methods like toSorted(), toSpliced(), and with() which are designed for immutable operations.

Next Steps

So far, we've focused entirely on managing state within a single component. But what happens when multiple components need to access or modify the same piece of data? In our next lesson, we will solve this exact problem by learning how to lift state up to a common ancestor to share state between sibling components. This is the primary mechanism for component communication in React.