Javascript – How to use Set with react’s useState

javascriptreactjs

I have an array that I have to add/remove elements from, and I figured I would use Set to accomplish this because of its add has and delete.

const [tags, setTags] = React.useState(new Set())

If I want to add something to tags, how can I do this with setTags? Or do I just call tags.add() ?

Best Solution

A Set is by definition mutable, React won't trigger a new render if you merely call const newSet = set.add(0) cause the shallow comparison between previous and new will always assert to true

You can use the spread operator to change references between each update yet still maintaining all of Set's behaviors

Adding an element

const [state, setState] = useState(new Set())

const addFoo = foo =>{
    setState(previousState => new Set([...state, foo]))
}

You could still use the add method since it returns the updated set

const addFoo = foo =>{
    setState(prev => new Set(prev.add(foo)))
}

Removing an element

Removing is a little trickier. You first need to turn it into an array, filter and spread the result

const removeFoo = foo =>{
    setState(prev => new Set([...prev].filter(x => x !== foo)))
}

For clarity

const removeFoo = foo =>{ 
    setState(prev =>{
        return prev.filter(x => x !== foo)
    })
}