---
id: 67d1ebcab4e0521a6654bb64
title: How Do You Update Arrays in State?
challengeType: 19
dashedName: how-do-you-update-arrays-in-state
---

# --description--

In React, updating arrays in state is quite straightforward, but it can be easy to make a mistake, especially if you're coming from vanilla JavaScript where you can modify arrays directly.

In React, state is treated as immutable so it can recognize changes and make the proper updates to the user interface.

Let's look at how you can update arrays held in state in React.

One of the most common mistakes when updating arrays in a React state is to directly modify the array using methods like `push()`, `pop()`, or `splice()`. These methods mutate the original array, and React does not allow that.

React relies on a new array reference to detect changes, so directly modifying the array can prevent the component from re-rendering as expected.

Here's an example of using the `push()` method to add to an array in state, which won't work:

```jsx
import { useState } from "react";

function ItemsList() {
  const [items, setItems] = useState([
    { id: 0, name: "Item 1" },
    { id: 1, name: "Item 2" },
    { id: 2, name: "Item 3" },
  ]);

  const addItem = () => {
    const newItem = { id: items.length + 1, name: `Item ${items.length + 1}` };
    items.push(newItem); // This modifies the original array
    setItems(items); // React will not detect this change
  };

  return (
    <div>
      <button onClick={addItem}>Add Item</button>
      <ul>
        {items.map((item) => (
          <li key={item.id}>{item.name}</li>
        ))}
      </ul>
    </div>
  );
}

export default ItemsList;
```

If you click the `Add Item` button, nothing happens in the user interface.

It might also be tempting to remove items from the array with the `pop()` method:

```js
const removeItem = () => {
  items.pop(); // Modifies the original array
  setItems(items); // React will not detect this change, either
};
```

To update an array in state, the key is to create a new array, do your operations, and pass that to React, rather than mutate the existing array.

Because it's a new array, React will know that the state has been changed, and trigger a re-render.

Here's how you can add to the `items` array using the spread operator:

```js
const addItem = () => {
  const newItem = {
    id: items.length + 1,
    name: `Item ${items.length + 1}`,
  };

  // Creates a new array
  setItems((prevItems) => [...prevItems, newItem]);
};
```

`[...prevItems, newItem]` creates a new array by copying all items in the existing `items` array held in state, then adds `newItem` at the end, which increments the `id` and the item number.

If you want to remove something from the array, you can use the `filter()` method, which returns a new array after filtering out whatever you want to remove:

```js
const removeItem = (id) => {
  setItems((prevItems) => prevItems.filter((item) => item.id !== id));
};
```

Here's the full code:

```jsx
import { useState } from "react";

function ItemsList() {
  const [items, setItems] = useState([
    { id: 0, name: "Item 1" },
    { id: 1, name: "Item 2" },
    { id: 2, name: "Item 3" },
  ]);

  const addItem = () => {
    const newItem = { id: items.length + 1, name: `Item ${items.length + 1}` };
    setItems((prevItems) => [...prevItems, newItem]); // Creates a new array
  };

  const removeItem = (id) => {
    setItems((prevItems) => prevItems.filter((item) => item.id !== id)); // Creates a new array
  };

  return (
    <div>
      <button onClick={addItem}>Add Item</button>
      <ul>
        {items.map((item) => (
          <li key={item.id}>
            {item.name}{" "}
            <button onClick={() => removeItem(item.id)}>Remove</button>
          </li>
        ))}
      </ul>
    </div>
  );
}

export default ItemsList;
```

Those are some common ways you can update an array in state.

# --questions--

## --text--

Which of the following is the correct way to update state and add new items to an array?

## --answers--

```js
setItems(copy [prevItems, newItem]);
```

### --feedback--

To update arrays in state you need to use the setter function and proper syntax for adding new items to an array.

---

```js
setItems(new Array = [...prevItems, newItem]);
```

### --feedback--

To update arrays in state you need to use the setter function and proper syntax for adding new items to an array.

---

```js
items = (prevItems) => [...prevItems, newItem];
```

### --feedback--

To update arrays in state you need to use the setter function and proper syntax for adding new items to an array.

---

```js
setItems((prevItems) => [...prevItems, newItem]);
```

## --video-solution--

4

## --text--

Why should you NOT directly modify an array in React state?

## --answers--

It automatically clears the array.

### --feedback--

React relies on immutability to detect changes in state.

---

It adds unwanted duplicates to the array.

### --feedback--

React relies on immutability to detect changes in state.

---

It causes errors in the component.

### --feedback--

React relies on immutability to detect changes in state.

---

It prevents React from detecting changes.

## --video-solution--

4

## --text--

Which method is best for removing an item from an array in React state?

## --answers--

`splice()`

### --feedback--

Think about a method that creates a new array without modifying the original.

---

`push()`

### --feedback--

Think about a method that creates a new array without modifying the original.

---

`pop()`

### --feedback--

Think about a method that creates a new array without modifying the original.

---

`filter()`

## --video-solution--

4
