How to delete an item from the state array in React?
Tags: react
Published: 2022-09-30 11:32:25

Have you started working on React recently and wanted to know the right way to delete an item from an array stored in the useState hook? You are at the right place!

{% embed https://youtu.be/_SpFlYZjYjk %}

## Setting up the project

First, let's create a react project using the following command:

```bash
npx create-react-app react-delete-usestate
```

Add the following styles to `index.css`:

```css
body {
  display: flex;
  justify-content: center;
}

ul {
  list-style-type: none;
  padding: 0;
}
li {
  padding: 6px 0;
  display: flex;
  justify-content: space-between;
}

button {
  margin-left: 20px;
}
```

Now, create an array of fruits, store them in useState hook, and display them along with a delete button.

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

function App() {
  const [fruits, setFruits] = useState([
    "🍎 Apple",
    "🍊 Orange",
    "🍌 Banana",
    "🍇 Grapes",
  ])
  return (
    <div className="App">
      <ul>
        {fruits.map(fruit => {
          return (
            <li key={fruit}>
              <span>{fruit}</span>
              <button>Delete</button>
            </li>
          )
        })}
      </ul>
    </div>
  )
}

export default App
```

If you run the app now, you should be able to see the list of fruits as shown below:

![list of fruits with delete button](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/tke8kngbdidhcnrxm3i6.png)

## Different ways of deleting

### Deleting by value

If you are sure that you have a unique list of items, then you can delete the item using the value:

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

function App() {
  const [fruits, setFruits] = useState([
    "🍎 Apple",
    "🍊 Orange",
    "🍌 Banana",
    "🍇 Grapes",
  ])
  const deleteByValue = value => {
    setFruits(oldValues => {
      return oldValues.filter(fruit => fruit !== value)
    })
  }
  return (
    <div className="App">
      <ul>
        {fruits.map(fruit => {
          return (
            <li key={fruit}>
              <span>{fruit}</span>
              <button onClick={() => deleteByValue(fruit)}>Delete</button>
            </li>
          )
        })}
      </ul>
    </div>
  )
}

export default App
```

Here, we are passing a callback to the `setFruits` function. Inside the callback, we are calling the [filter function](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter), which filters all the values except the one passed to the `deleteByValue`, hence deleting the passed value.

### Deleting by index

If you think you can have duplicate values and you want to delete them by the array index, you can achieve it in a similar fashion.

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

function App() {
  const [fruits, setFruits] = useState([
    "🍎 Apple",
    "🍊 Orange",
    "🍌 Banana",
    "🍇 Grapes",
  ])
  const deleteByIndex = index => {
    setFruits(oldValues => {
      return oldValues.filter((_, i) => i !== index)
    })
  }
  return (
    <div className="App">
      <ul>
        {fruits.map((fruit, index) => {
          return (
            <li key={fruit}>
              <span>{fruit}</span>
              <button onClick={() => deleteByIndex(index)}>Delete</button>
            </li>
          )
        })}
      </ul>
    </div>
  )
}

export default App
```

### Deleting an object from the array

If you have an array of objects and you want to delete them based on the id of the object, you can do so by using the following code:

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

function App() {
  const [fruits, setFruits] = useState([
    { id: 1, name: "🍎 Apple" },
    { id: 2, name: "🍊 Orange" },
    { id: 3, name: "🍌 Banana" },
    { id: 4, name: "🍇 Grapes" },
  ])
  const deleteById = id => {
    setFruits(oldValues => {
      return oldValues.filter(fruit => fruit.id !== id)
    })
  }
  return (
    <div className="App">
      <ul>
        {fruits.map(fruit => {
          return (
            <li key={fruit.id}>
              <span>{fruit.name}</span>
              <button onClick={() => deleteById(fruit.id)}>Delete</button>
            </li>
          )
        })}
      </ul>
    </div>
  )
}

export default App
```

My favorite way of deleting is deleting by id, followed by the index. Let me know which is your favorite in the comments below 👇.