DEV Community

Cover image for React Tricks Miniseries 4: How to remove element from useState array
Uriel Bitton
Uriel Bitton

Posted on • Edited on

React Tricks Miniseries 4: How to remove element from useState array

The useState hook in react works wonders and can be used to manipulate variables of various data types.

However, the trickiest to manipulate is probably array types. Pushing to, removing from and editing an array in javascript is rather simple but with useState it becomes a little complex, especially if you are following react's best practices for state.

Let's see how we can perform these best practices to add, remove and edit an array that is a state.

Pushing

This one is mostly simple and most developers do it correctly. It is simply a matter of making use of the previous state and adding your element after the previous elements like so:

setFruits(prev => [...prev, 'apple'])
Enter fullscreen mode Exit fullscreen mode

Removing

Removing is where it gets complicated. Over the years i have seen many developers use all kinds of non best practices 'hacks' to achieve this. There was even a very popular and accepted answer on Stack Overflow that was also not best practice for useState. It suggested to perform regular javascript array.splice() and then update the state with setState(prev => [...prev]). Not good!

All these solutions definitely did work, but if you want to follow react's best practice then here is how to do remove from an array:

Solution

The idea is to never mutate the state in setState in react. So you always need to use the previous value. Thus removing an element from a state array in react should be performed like this:

let elementToRemove = 'orange'
setFruits(prev => prev.filter(fruit => fruit !== elementToRemove ))
Enter fullscreen mode Exit fullscreen mode

In a single line we can remove the element we wanted, without using javascript methods, or mutating our state.
You can test it out for yourself!

Conclusion

Removing an element from a state array is simple and done in one line but needs to be carefully performed without mutating the state in order to follow best react practices.

Top comments (2)

Collapse
 
midhunvijayvs profile image
midhunvijayvs

It is poping an error 'filter not defined'

Collapse
 
urielbitton profile image
Uriel Bitton

you need to declare the useState array before.