A custom hook for managing boolean state with convenient toggle, open, and close functions.
src/hooks/use-toggle.ts
function useToggle(initialState?: boolean): [boolean, { toggle: () => void; close: () => void; open: () => void; }]initialState(optional): Initial boolean state. Defaults tofalse.
Returns a tuple with:
state: Current boolean stateactions: Object containing:toggle(): Flips the current stateclose(): Sets state tofalseopen(): Sets state totrue
import { useToggle } from '@/hooks/use-toggle';
function MyComponent() {
const [isOpen, { toggle, close, open }] = useToggle(false);
return (
<div>
<p>Modal is {isOpen ? 'open' : 'closed'}</p>
<button onClick={toggle}>Toggle Modal</button>
<button onClick={open}>Open Modal</button>
<button onClick={close}>Close Modal</button>
</div>
);
}- Memoized callbacks: All action functions are memoized with
useCallbackto prevent unnecessary re-renders - TypeScript support: Fully typed with proper return type inference
- Flexible initial state: Can start with any boolean value
- Modal/dialog visibility
- Dropdown menu state
- Sidebar toggle
- Form field visibility
- Loading states
- Feature flags
- Uses React's
useStatefor state management - All callbacks are wrapped in
useCallbackfor performance optimization - Returns a tuple for easy destructuring with custom names