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);
})
}