Implement a useSet hook that manages a JavaScript Set of items with additional utility methods.

It is more convenient to use useSet over plain useState because in the latter case, you would always have to create a new Set, mutate it, then set state to use the new set, which can be quite cumbersome.

The hook should work generically with items of any types.

export default function Component() {
  const { set, add, remove, toggle, reset, clear } = useSet(new Set(['hello']));

  return (
    <div>
      <button onClick={() => add(Date.now().toString())}>Add</button>
      <button onClick={() => remove('hello')} disabled={!has('hello')}>
        Remove 'hello'
      </button>
      <button onClick={() => toggle('hello')}>Toggle hello</button>
      <button onClick={() => reset()}>Reset</button>
      <button onClick={() => clear()}>Clear</button>
      <pre>{JSON.stringify(Array.from(set), null, 2)}</pre>
    </div>
  );
}

Arguments

Returns

The hook returns an object with the following properties:

Editorial