useSet
A React hook that manages a Set as state. Provides efficient state management and stable action functions.
Interface
ts
function useSet<T>(
initialState?: SetOrValues<T>
): [Omit<Set<T>, 'add' | 'clear' | 'delete'>, SetActions<T>];Parameters
- initialStateSet<T> | T[]
Initial Set state (Set object or array of values). Defaults to an empty Set.
Return Value
- [Set, SetActions]
A tuple containing the Set state and actions to manipulate it.
- [0]Omit<Set<T>, add | clear | delete>
The current Set state with mutation methods hidden.
- [1].add(value: T) => void
Adds a value to the set.
- [1].remove(value: T) => void
Removes a value from the set.
- [1].toggle(value: T) => void
Adds the value if absent, removes it if present.
- [1].setAll(values: Set<T> | T[]) => void
Replaces all values in the set.
- [1].reset() => void
Resets the set to its initial state.
- [0]Omit<Set<T>, add | clear | delete>
Example
tsx
function TagSelector() {
const [selectedTags, { add, remove, toggle }] = useSet<string>(['react']);
return (
<div>
{['react', 'vue', 'svelte'].map(tag => (
<button key={tag} onClick={() => toggle(tag)}>
{selectedTags.has(tag) ? '✓' : ''} {tag}
</button>
))}
</div>
);
}