DEV Community

Discussion on: Using Javascript Sets with React useState

Collapse
 
petemcfarlane profile image
Pete McFarlane

I fell into this very trap yesterday, spent a while trying to work out why modifying my set didn’t cause the state to update.

It’s a pity that set isn’t immutable by default, perhaps for performance reasons?

I do prefer the has(), add(), delete() syntax but it’d be even nicer if they just returned a new, immutable set in place, rather than having to pass the results to a new Set(currentSet) again.

I might revisit just using an array with a filter
setState(currentState.includes(val) ? currentState.filter(x => x !== val) : [val, ...currentState])
Although apparently IE doesn’t support Array.includes()...