useToggle
Toggles between two values.
Toggles between two values.
Import
import { useToggle } from '@kamod-ch/hooks'Live demo
Basic demo
Toggles between two values.
Layout: list
import { useToggle } from '@kamod-ch/hooks'
export default function UseToggleDemo() {
const [value, actions] = useToggle('list', 'grid')
return (
<div>
<p><strong>Layout:</strong> {value}</p>
<div class="demo-actions">
<button type="button" onClick={actions.toggle}>Toggle</button>
<button type="button" onClick={actions.setLeft}>Set list</button>
<button type="button" onClick={actions.setRight}>Set grid</button>
</div>
</div>
)
}
API
TypeScript signature
export interface Actions<T> {
setLeft: () => void;
setRight: () => void;
set: (value: T) => void;
toggle: () => void;
}
declare function useToggle<T = boolean>(): [boolean, Actions<T>];
declare function useToggle<T>(defaultValue: T): [T, Actions<T>];
declare function useToggle<T, U>(defaultValue: T, reverseValue: U): [T | U, Actions<T | U>];
export default useToggle;
/SSR considerations
This hook is safe to import during SSR. If your effect body touches the DOM, keep that work inside the effect callback.
Browser compatibility
Works in any modern browser supported by Preact.