useToggle
useToggle is a custom React hook that manages a boolean state and provides a stable function to toggle it or force it to a specific value.
Usage
import { useToggle } from "hookify-react";
export default function UseToggleExample() {
const [isToggled, toggle] = useToggle(false);
return (
<div>
<button onClick={() => toggle()}>Toggle</button>
<button onClick={() => toggle(true)}>On</button>
<button onClick={() => toggle(false)}>Off</button>
<p>Toggle is: {isToggled ? "On" : "Off"}</p>
</div>
);
}
API Reference
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
initialValue | boolean | false | The initial boolean state. Optional; defaults to false. |
Return Value
useToggle returns a tuple [state, toggle].
| Property | Type | Description |
|---|---|---|
state | boolean | The current boolean state. |
toggle | (value?: boolean) => void | Flips the state when called with no argument, or sets it explicitly when passed true/false. |
Behavior
initialValueis optional and defaults tofalse.- Calling
toggle()with no argument flips the current value. - Calling
toggle(true)ortoggle(false)forces the state to that value. - The
togglefunction has a stable identity across renders.