React useSet hook

React, Hooks, State · Nov 1, 2021

Creates a stateful Set object, and a set of functions to manipulate it.

  • Use the useState() hook and the Set constructor to create a new Set from the initialValue.
  • Use the useMemo() hook to create a set of non-mutating actions that manipulate the set state variable, using the state setter to create a new Set every time.
  • Return the set state variable and the created actions.
const useSet = initialValue => {
  const [set, setSet] = React.useState(new Set(initialValue));

  const actions = React.useMemo(
    () => ({
      add: item => setSet(prevSet => new Set([...prevSet, item])),
      remove: item =>
        setSet(prevSet => new Set([...prevSet].filter(i => i !== item))),
      clear: () => setSet(new Set()),
    }),
    [setSet]
  );

  return [set, actions];
};
const MyApp = () => {
  const [set, { add, remove, clear }] = useSet(new Set(['apples']));

  return (
    <div>
      <button onClick={() => add(String(Date.now()))}>Add</button>
      <button onClick={() => clear()}>Reset</button>
      <button onClick={() => remove('apples')} disabled={!set.has('apples')}>
        Remove apples
      </button>
      <pre>{JSON.stringify([...set], null, 2)}</pre>
    </div>
  );
};

ReactDOM.createRoot(document.getElementById('root')).render(
  <MyApp />
);

Written by Angelos Chalaris

I'm Angelos Chalaris, a JavaScript software engineer, based in Athens, Greece. The best snippets from my coding adventures are published here to help others learn to code.

If you want to keep in touch, follow me on GitHub.

More like this

  • React useMap hook

    Creates a stateful Map object, and a set of functions to manipulate it.

    React, Hooks · Nov 6, 2021

  • React useGetSet hook

    Creates a stateful value, returning a getter and a setter function.

    React, Hooks · Oct 27, 2021

  • React useMergeState hook

    Creates a stateful value, and a function to update it by merging the new state provided.

    React, Hooks · Sep 23, 2021