skip to Main Content

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


  1. If you want to use a Set object with the useState hook you can just do

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

    Please 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 call setProducts with a new Set. Depending on your requirements, a Set object may not be the best option!

    Login or Signup to reply.
  2. Maybe just something simple like:

    let newProduct = 'new product';
    setProducts(prev => (prev.includes(newProduct) ? [...products] : [...products, newProduct]));
    
    Login or Signup to reply.
  3. 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
    })
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search