useToggle
useToggle manages a boolean with three named actions: enable, disable and toggle. Use it for open/closed
and on/off state when named actions read better than setState(!value).Hooks
Signature
const { active, enable, disable, toggle } = useToggle(initialState?, opt?);Name | Type | Description |
|---|---|---|
initialState | boolean | (() => boolean) | Initial value or a lazy factory. Default false. |
opt.onActive | () => void | Runs whenever the state becomes true. |
returns | { active, enable, disable, toggle } | The current value and the three actions. |
Scrolls sideways inside the table. The page does not.
Example
import { useToggle } from '@apollion-dsi/core/hooks';
function Disclosure() {
const { active: open, toggle, disable } = useToggle(false);
return (
<>
<button onClick={toggle} aria-expanded={open}>
Details
</button>
{open && <div onClick={disable}>Details content</div>}
</>
);
}Pitfalls
enable,disableandtoggleare new functions on every render. Keep them out of effect dependencies and memoized props, or wrap them withuseEventCallback.onActiveruns inside the state update. React may call it twice in Strict Mode, so keep it free of side effects that must not repeat.