Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to use a Set data structure as a state in React Typescript?

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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:

const next = new Set(prev) // prev is 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:

const [products, setProducts] = React.useState<String[]>(() => new Set())

Adding a value to the state:

setProducts(prev => {
  const next = new Set(prev) // create a new Set from the old one
  
  next.add(val) // add a value to the new Set

  return next
})

Removing a value from the state:

setProducts(prev => {
  const next = new Set(prev) // create a new Set from the old one

  next.delete(val) // remove a value from the new Set

  return next
})
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading