useToggle
Hook for managing a boolean state with explicit actions. Clearer than a
useState<boolean> when you need "turn on", "turn off" and "invert" in
different places of the component.
Accepts the initial state as a value or a lazy factory and supports an
onActive callback fired whenever the state becomes true.
When to use
| ✅ Use when… | 🚫 Avoid when… |
|---|---|
|
|
Signature
const { active, enable, disable, toggle } = useToggle(
initialState?: boolean | (() => boolean),
opt?: { onActive?: () => void },
);Example
import { useToggle } from '@apollion-dsi/core/hooks';
function Menu() {
const { active: open, enable, disable, toggle } = useToggle(false);
return (
<>
<button onClick={toggle}>{open ? 'Close' : 'Open'}</button>
{open && <div onClick={disable}>menu content</div>}
</>
);
}See also
- Full API:
useToggle(reference generated from TSDoc).