useSet
The useSet hook manages a Set as React state. Every change produces a new Set instance, so it works correctly in dependency arrays and with React.memo. It is a great fit for selections, tags, and checkbox groups.
Usage
Installation
import { useSet } from "hookstorm";
Parameters
- initialValues — (optional) Initial values, for example
[1, 2]or an existingSet.
Return Values
- set — The current
Set. Treat it as read-only and update it through the actions below. - add(value) — Adds a value.
- remove(value) — Deletes a value.
- toggle(value) — Adds the value if it is missing, removes it otherwise.
- has(value) — Returns
trueif the value is in the set. - clear() — Removes all values.
- reset() — Restores the initial values.
Example Usage
import { ReactElement } from "react";
import { useSet } from "hookstorm";
const OPTIONS = ["React", "Vue", "Svelte"];
export default function FrameworkPicker(): ReactElement {
const { set: selected, toggle, clear } = useSet<string>();
return (
<div>
{OPTIONS.map((name) => (
<label key={name}>
<input
type="checkbox"
checked={selected.has(name)}
onChange={() => toggle(name)}
/>
{name}
</label>
))}
<p>Selected: {Array.from(selected).join(", ") || "none"}</p>
<button onClick={clear}>Clear</button>
</div>
);
}
Notes
- Adding an existing value or removing a missing one does not cause a re-render.
resetuses the values from the first render; later changes toinitialValuesare ignored.