useToggle
A React hook for managing boolean state with convenient toggle actions.
Overview
useToggle simplifies boolean state management by providing a tuple with the current value and an object containing helper actions. Perfect for modals, dropdowns, accordions, theme switches, and any on/off UI patterns.
Demo
API Reference
function useToggle(initialValue?: boolean): [
boolean,
{
toggle: () => void,
setTrue: () => void,
setFalse: () => void,
setValue: (value: boolean) => void
}
]Parameters
| Name | Type | Description |
|---|---|---|
initialValue | boolean | Optional. Initial toggle state. Defaults to false. |
Returns
| Name | Type | Description |
|---|---|---|
value | boolean | The current boolean state. |
toggle | () => void | Flips the current value. |
setTrue | () => void | Sets value to true. |
setFalse | () => void | Sets value to false. |
setValue | (value: boolean) => void | Sets value directly. |
Usage Examples
Modal Control
import { useToggle } from 'react-hooks-ts'
function ModalExample() {
const [isOpen, { setTrue: open, setFalse: close }] = useToggle()
return (
<>
<button onClick={open}>Open Modal</button>
{isOpen && <Modal onClose={close} />}
</>
)
}Theme Switch
import { useToggle } from 'react-hooks-ts'
function ThemeSwitch() {
const [isDark, { toggle }] = useToggle(false)
return (
<button onClick={toggle}>
{isDark ? '🌙 Dark' : '☀️ Light'}
</button>
)
}Features
- 🎯 Simple API - Destructure only the actions you need.
- 🔄 Memoized Actions - All functions maintain stable references.
- ⚡ Zero Dependencies - Lightweight and fast.
- 💪 TypeScript Ready - Full type inference out of the box.