Explain Codes LogoExplain Codes Logo

How to delete an item from state array?

javascript
react
state-management
immutability
Alex KataevbyAlex Kataev·Feb 16, 2025
TLDR

Here's a swift way to remove an item from a state array with the filter method. When dealing with a React state, apply the setState function with an argument that omits the target item by its unique identifier:

const removeItemById = (idToRemove) => { setState(currentState => currentState.filter(item => item.id !== idToRemove)); };

Trigger removeItemById with the id of the unrequired item. The filter retains only those items not associated with the id.

The holy grail of immutability

React queries upon a golden truth - 'state mutations are evil'. This is because React harnesses shallow comparison within the virtual DOM to identify changes. Alterations through mutation could lead to unpredictable output and obstruct React's intrinsic performance boosts.

Clone wars: Spread syntax for the win

Ensure unyielding immutability by creating a twin array using spread syntax prior to modification:

const removeItemByIndex = (indexToRemove) => { // It's like snap, but for arrays setState(prevState => [ ...prevState.slice(0, indexToRemove), ...prevState.slice(indexToRemove + 1) ]); };

Here, we are birthing a fresh array with all items except the outcast at indexToRemove.

To splice or not to splice

Though splice can be a viable contender for removing items, its mutation abilities can turn rogue. If you choose splice, ensure it operates on a clone array and not the state's original array:

// Splicing array like a pumpkin on Halloween const removeItemBySplice = (indexToRemove) => { setState(prevState => { const newArray = [...prevState]; newArray.splice(indexToRemove, 1); return newArray; }); };

Must avoid traps in the matrix

Verify before evict

Prior to attempting removal, verify the item's existence. This could save you from unnecessary state updates and missing items in your state array:

const removeItemIfExist = (itemToRemove) => { // Let's not remove what doesn't exist, shall we? setState(prevState => { const index = prevState.indexOf(itemToRemove); return index !== -1 ? [ ...prevState.slice(0, index), ...prevState.slice(index + 1) ] : prevState; }); };

Bind for a shining armor

Ensure your armor, like removePeople, binds well to your component's context. Conversely, let arrow functions do the needful:

class MyComponent extends React.Component { removeItem = (idToRemove) => { // Arrow functions to save the day! this.setState(prevState => ( prevState.filter(item => item.id !== idToRemove) )); }; // ... }

Event-driven removal

Rain down event-driven removals by fetching the target item via e.target.value from the Event Object:

handleRemoveClick = (event) => { // See you next event! const idToRemove = event.target.value; this.removeItemId(idToRemove); };

Lifecycle method integration class components

Blend the removal logic with component lifecycle methods for a perfect balance:

componentDidUpdate(prevProps, prevState) { if (this.state.items.length < prevState.items.length) { // Well, an item just left the Arrays' party } }