useToggle
Controls a boolean state with a toggle function.
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
onToggle
callback 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]
. value
is the current boolean state.toggle
is a function that toggles the state betweentrue
andfalse
.
Initial Value
- The
initialValue
prop 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
onToggle
callback 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);
});