I want to initialize a React state as an empty Set in Typescript, and then add/remove values.
If I wanted to use an array, I would do this:
const [products, setProducts] = React.useState<String[]>([])
// And then to change it:
setProducts([...products, "new product"])
But I want to use a Set, so every value has to be unique. How can I do this?
3
Answers
If you want to use a Set object with the
useState
hook you can just doPlease note
React will not re-render if state is mutated i.e. if you do something like
products.add(something)
it will not trigger a re-render. In order to trigger a re-render you will have to callsetProducts
with a newSet
. Depending on your requirements, aSet
object may not be the best option!Maybe just something simple like:
A Set is a mutable data structure, while the state should be immutable. When you need to update the state, first create a new Set off the old Set:
Now you can update the new Set (
next
), and set it as the new state.Initializing the state once using an initializer function:
Adding a value to the state:
Removing a value from the state: