typescriptbeginner
useToggle Hook
Simple boolean toggle hook with set, toggle, on, and off functions.
typescriptPress ⌘/Ctrl + Shift + C to copy
import { useState, useCallback } from 'react';
export function useToggle(initialValue = false) {
const [value, setValue] = useState(initialValue);
const toggle = useCallback(() => setValue(v => !v), []);
const on = useCallback(() => setValue(true), []);
const off = useCallback(() => setValue(false), []);
return { value, toggle, on, off, setValue } as const;
}
// Usage:
// const { value: isOpen, toggle, off: close } = useToggle();Use Cases
- Modal open/close state
- Sidebar toggles
Tags
Related Snippets
Similar patterns you can reuse in the same workflow.
typescriptbeginner
usePrevious Hook
Track the previous value of any state or prop using a ref-based hook for comparison logic.
Best for: Detecting value changes
#hooks#state
typescriptintermediate
useUndoRedo State History Hook
Add undo/redo capability to any state with history tracking, max size limits, and keyboard shortcuts.
Best for: Text editor undo/redo
#react#hooks
typescriptintermediate
useLocalStorage — Persistent State Hook
Sync React state with localStorage including SSR safety, JSON serialization, and cross-tab updates.
Best for: User preferences
#hooks#localstorage
typescriptintermediate
useFormValidation Hook
Lightweight form validation hook with field-level errors, touched tracking, and submit handling.
Best for: Contact forms
#hooks#forms