Skip to content
Advertisement

‘splice’ instead of ‘filter’

I have a field for entering tags. It is also possible to remove tags. And here I have a question.

My deletion code is below. Tags can be deleted one at a time, in any order (first, last, somewhere in the middle, it doesn’t matter).

 const deleteTag = (index) => {
      setTags((prevState) => prevState.filter((tag, i) => i !== index));
    };
  

But I would like to use ‘splice’ instead of ‘filter’. With the same functionality. Tell me how to do it

Advertisement

Answer

Splice’s first argument is the item index, and the second argument is how many items you want to delete from that index.

const deleteTag = (index) => {
  setTags((prevState) => {
    prevState.splice(index, 1)
    return [...prevState]
   });
 };

UPDATE

If you are using <StrictMode> the setState will execute twice and will delete two items instead of one.

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement