#hooks
67 snippets tagged with #hooks
useFetch — Generic Data Fetching Hook
Custom React hook for data fetching with loading, error, and refetch states using the Fetch API.
Best for: API data fetching
useDebounce — Debounced Value Hook
Debounce any rapidly-changing value with a configurable delay. Useful for search inputs and resize handlers.
Best for: Search-as-you-type
useLocalStorage — Persistent State Hook
Sync React state with localStorage including SSR safety, JSON serialization, and cross-tab updates.
Best for: User preferences
useClickOutside — Outside Click Detection
Detect clicks outside a referenced element to close dropdowns, modals, and popover menus.
Best for: Dropdown menus
useMediaQuery — Responsive Breakpoint Hook
Subscribe to CSS media query changes and get a boolean flag for responsive rendering logic in React.
Best for: Responsive layouts
Infinite Scroll with Intersection Observer
Load more items as the user scrolls using IntersectionObserver. No external libraries required.
Best for: Feed pagination
useIntersectionObserver Hook
Track element visibility with the Intersection Observer API for lazy loading and scroll animations.
Best for: Lazy loading images
usePrevious Hook
Track the previous value of any state or prop using a ref-based hook for comparison logic.
Best for: Detecting value changes
useWindowSize Hook
Track browser window dimensions with debounced resize handling for responsive component logic.
Best for: Responsive layouts
useCopyToClipboard Hook
Copy text to clipboard with success state and automatic reset timer using the Clipboard API.
Best for: Copy code snippets
useFormValidation Hook
Lightweight form validation hook with field-level errors, touched tracking, and submit handling.
Best for: Contact forms
React Custom Hook for Data Fetching
A reusable useFetch hook with loading states, error handling, caching, and abort support.
Best for: Reusable data fetching across components
React Form Validation Hook
A type-safe form validation hook with field-level errors, dirty tracking, and submit handling.
Best for: Type-safe form handling without libraries
React Intersection Observer Hook
Custom useIntersectionObserver hook for lazy loading, infinite scroll, and scroll animations.
Best for: Lazy loading components when they enter viewport
React Responsive Breakpoint Hook
A useMediaQuery hook for responsive rendering with SSR-safe breakpoint detection.
Best for: Conditional rendering based on screen size
useThrottle Hook for Rate Limiting
Throttle rapidly-firing values like scroll or resize events with a configurable delay hook.
Best for: Scroll position tracking
useAsync Hook for Promise Management
Manage async operations with loading, error, and data states using a reusable hook pattern.
Best for: Data fetching with status tracking
useKeyboardShortcut Hook
Register global keyboard shortcuts with modifier keys, preventing defaults, and cleanup on unmount.
Best for: Command palette shortcuts
useMutation Hook for Side Effects
Handle mutations (POST/PUT/DELETE) with loading, error, reset, and optimistic update support.
Best for: Form submission handling
useInfiniteQuery Hook
Implement infinite scrolling with cursor-based pagination, loading states, and intersection observer.
Best for: Infinite scroll feeds
useEventListener Hook
Safely add and clean up DOM event listeners with a type-safe hook supporting window, document, and elements.
Best for: Window resize handling
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
useInterval Hook
Declarative setInterval hook that handles cleanup and dynamic delay changes safely.
Best for: Polling APIs
useTimeout Hook
Declarative setTimeout hook with automatic cleanup and reset capabilities.
Best for: Auto-dismiss notifications
useToggle Hook
Simple boolean toggle hook with set, toggle, on, and off functions.
Best for: Modal open/close state
useHover Hook
Tracks whether an element is being hovered using mouse enter/leave events with a ref.
Best for: Tooltip triggers
useOnlineStatus Hook
Tracks browser online/offline status and re-renders when connectivity changes.
Best for: Offline-first apps
useScrollPosition Hook
Tracks window scroll position with throttling for performance-sensitive scroll effects.
Best for: Sticky headers
useLockBodyScroll Hook
Locks body scroll when active, commonly used with modals and overlays to prevent background scrolling.
Best for: Modal dialogs
useDocumentTitle Hook
Dynamically updates the document title and restores it on unmount.
Best for: Page title updates
useFocusTrap Hook
Traps keyboard focus within a container for accessible modals and dialogs.
Best for: Accessible modals
useIdleDetection Hook
Detects user inactivity after a configurable timeout by monitoring mouse, keyboard, and touch events.
Best for: Auto-logout
useStepWizard Hook
Multi-step wizard hook that manages step navigation, validation gates, and completion state.
Best for: Onboarding flows
useClipboard Hook (Advanced)
Clipboard hook with read, write, and auto-reset of the copied state after a timeout.
Best for: Copy-to-clipboard buttons
useFetch with Cache Hook
Data fetching hook with built-in cache, loading, error states, and automatic revalidation.
Best for: API data fetching
useDarkMode Hook
Dark mode hook that syncs with system preferences and persists user choice to localStorage.
Best for: Theme switching
usePermission Hook
Queries and tracks browser permission state for features like notifications, camera, and geolocation.
Best for: Permission-gated features
useMutationObserver Hook
Wraps the MutationObserver API in a React hook to observe DOM changes on a target element.
Best for: Third-party widget monitoring
useCountdown Hook
Countdown timer hook with start, pause, reset, and formatted time remaining output.
Best for: OTP expiry timers
useResizeObserver Hook
Tracks element dimensions using ResizeObserver with debounced updates.
Best for: Responsive layouts
useGeolocation Hook
Accesses browser geolocation API with loading, error states, and watch mode support.
Best for: Location-based features
useLongPress Hook
Detects long press gestures on touch and mouse devices with configurable threshold.
Best for: Context menus
useSearchParamsState Hook
Syncs component state with URL search parameters for shareable filter/sort states.
Best for: Filter state persistence
useWebSocket Hook
WebSocket hook with auto-reconnect, message queuing, and connection state tracking.
Best for: Chat applications
Infinite Scroll Hook v2
Intersection Observer-based infinite scroll with loading, error, and hasMore states.
Best for: Feed-style content
useHistoryState Hook
State hook that maintains full history with undo, redo, and time-travel capabilities.
Best for: Drawing apps
useMediaRecorder Hook
Wraps the MediaRecorder API for audio/video recording with start, stop, and blob output.
Best for: Voice memos
useSelectionRange Hook
Tracks user text selection within a container, returning selected text and range coordinates.
Best for: Text annotation tools
useIndexedDB Hook
Simple IndexedDB wrapper hook for persistent client-side storage with get, set, and delete.
Best for: Offline data storage
useTransitionGroup Hook
Manages enter/exit animations for list items with staggered transitions.
Best for: Animated list additions/removals
useSpeechSynthesis Hook
Text-to-speech hook using the Web Speech API with voice selection, rate, and pitch control.
Best for: Accessibility features
useNetworkSpeed Hook
Monitors the Network Information API to report connection type, downlink speed, and effective type.
Best for: Adaptive media quality
usePrefetch Hook
Prefetches data or resources when the user hovers over an element to reduce perceived latency.
Best for: Route prefetching
useAbortController Hook
Creates and manages AbortController instances for cancelling fetch requests on unmount.
Best for: Cancelling stale requests
usePageVisibility Hook
Detects when the page is hidden or visible using the Page Visibility API.
Best for: Pausing animations
useDebouncedCallback Hook
Returns a debounced version of a callback that delays execution until the pause in calls.
Best for: Search input debouncing
useScreenWakeLock Hook
Prevents the screen from turning off using the Screen Wake Lock API.
Best for: Video playback
useBreakpoints Hook
Returns the current Tailwind-style breakpoint based on window width for responsive logic.
Best for: Responsive component logic
useThrottledValue Hook
Throttles a rapidly changing value to update at most once per specified interval.
Best for: Scroll position tracking
useStorageEvent Hook
Syncs state across browser tabs by listening to localStorage storage events.
Best for: Theme sync across tabs
useFormDirty Hook
Tracks whether a form has unsaved changes and warns before page unload.
Best for: Form unsaved-changes warning
useFullscreen Hook
Toggle fullscreen mode on an element using the Fullscreen API with state tracking.
Best for: Video players
useClickAway Hook
Fires a callback when a click is detected outside the referenced element.
Best for: Dropdown close on outside click
usePersistentState Hook
Like useState but persists to localStorage with JSON serialization and SSR safety.
Best for: Persisting user preferences
useIsomorphicLayoutEffect Hook
Safely uses useLayoutEffect on client and useEffect on server to avoid SSR warnings.
Best for: DOM measurement before paint
Git Hooks Pre-Commit Example
Git pre-commit and commit-msg hooks to enforce linting, tests, and commit message conventions.
Best for: Enforcing code quality before commits
Git Hooks — Pre-Commit Lint and Format
Set up pre-commit hooks to automatically lint, format, and validate code before every commit.
Best for: Enforcing code quality before commits