DEV Community

Cover image for How to delete an item from the state array in React?
collegewap
collegewap

Posted on • Updated on • Originally published at codingdeft.com

How to delete an item from the state array in React?

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!

Setting up the project

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



npx create-react-app react-delete-usestate


Enter fullscreen mode Exit fullscreen mode

Add the following styles to index.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;
}


Enter fullscreen mode Exit fullscreen mode

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



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


Enter fullscreen mode Exit fullscreen mode

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

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:



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


Enter fullscreen mode Exit fullscreen mode

Here, we are passing a callback to the setFruits function. Inside the callback, we are calling the filter function, 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.



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


Enter fullscreen mode Exit fullscreen mode

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:



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


Enter fullscreen mode Exit fullscreen mode

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

Top comments (4)

Collapse
 
balaramgayen profile image
Balaram Gayen

Thank you for the help.
Mine is deleting by index

Collapse
 
devflivian profile image
Flivian mwirigi

Thanks for the article it was so intuitive and clear

Collapse
 
khatrinitesh profile image
Nitesh Khatri

I got resolved above that. Thank you for the help.

Collapse
 
ibesarah profile image
Ibe-Sarah

Mine is deleting by index. Thanks for this!