How to Delete Element from useState Array By Index in JavaScript

Published Jan 24, 2022  ∙  Updated May 18, 2022

How can we delete an element from an array stored in our component state in JavaScript?

Suppose we’re working in React.js or Next.js, and we have an array stored in our component state.

const [users, setUsers] = useState([]);

First, we need to know how to get a subarray from an array in JavaScript.

Get subarray from array in JavaScript

Suppose we have an array arr with 4 elements.

If we want to get the middle 2 elements in the array, we can use slice().

const arr = [1,2,3,4];
const subarr = arr.slice(1,3); // [2,3]

The first argument is the start index, inclusive.

The second argument is the stop index, exclusive.

This means that slice(1,3) is obtaining the array over indexes [1,3).

Remove element from state array by index

Finally, we can remove an element from a state array using this slice() function as well as the spread operator.

const removeUser = (index) => {
  setUsers([
    ...users.slice(0, index),
    ...users.slice(index + 1, users.length)
  ]);
}

We’re keeping all the values up to, but not including, the index.

Then, we’re keeping all the values from index + 1 to the end of the array.

Feel free to read about how to add elements to a useState array and update objects in a useState array.