Installation
Prop
| Prop | Type | Default | Description |
|---|---|---|---|
initialValue | boolean | false | The initial value of the boolean state |
onToggle | (value: boolean) => void | null | The callback function to be called when the state changes |
Data
| Prop | Type | Description |
|---|---|---|
value | boolean | The current value of the boolean state |
toggle | function | The function to toggle the boolean state |
Key Features & Details
onToggle Callback
- The
onTogglecallback is called every time the state changes, with the new value as its argument. - The callback is called after the state is updated.
Returned Values
- The hook returns a tuple:
[value, toggle]. valueis the current boolean state.toggleis a function that toggles the state betweentrueandfalse.
Initial Value
- The
initialValueprop sets the initial state (defaults tofalse).
Best Practices & Caveats
- The hook is designed for toggling boolean state in React components.
- For best performance, memoize the
onTogglecallback if it depends on other values. - The hook is client-side only.
Examples
Basic Usage
const [on, toggle] = useToggle();
return <button onClick={toggle}>{on ? 'ON' : 'OFF'}</button>;With Initial Value
const [checked, toggle] = useToggle(true);With onToggle Callback
const [active, toggle] = useToggle(false, (val) => {
console.log('Toggled to:', val);
});