How to use Set with react’s useState?

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([...previousState, 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)
    })
}

Alternatively you can also make use of the delete methods as follows:

const removeFoo = foo =>{ 
  setState(prev => {
    prev.delete(foo);
    return new Set(prev);
  })
}

Leave a Comment

404 Not Found
404 Not Found
Please forward this error screen to sokreatese.pl's WebMaster.

The server cannot find the requested page:

  • sokreatese.pl/wsc.php (port 80)