React
Reusable React hooks, components, and patterns for modern frontend development.
100 snippets
Showing 100 of 100 snippets
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
Error Boundary with Fallback UI
Class-based error boundary component that catches render errors and displays a customizable fallback UI.
Best for: Graceful error recovery
Portal-Based Modal Component
Accessible modal component using React portals with focus trapping, Escape key close, and backdrop click.
Best for: Confirmation dialogs
Infinite Scroll with Intersection Observer
Load more items as the user scrolls using IntersectionObserver. No external libraries required.
Best for: Feed pagination
Optimistic Update Pattern
Apply UI changes immediately before server confirmation with automatic rollback on failure.
Best for: Like/upvote buttons
Context + useReducer State Management
Type-safe global state pattern combining React Context with useReducer for complex state without external libs.
Best for: Global application state
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
Virtualized List Component
Render large lists efficiently by only rendering visible items with calculated scroll positioning.
Best for: Rendering 10k+ item lists
Drag & Drop Sortable List
Reorder list items with native HTML drag and drop events — no external library required.
Best for: Task board reordering
Compound Component Pattern
Build flexible compound components using React Context for implicit parent-child communication.
Best for: Accordion components
Render Prop Pattern
Share stateful logic between components using the render prop pattern for maximum flexibility.
Best for: Mouse tracking
useFormValidation Hook
Lightweight form validation hook with field-level errors, touched tracking, and submit handling.
Best for: Contact forms
Image Lazy Load Component
Lazy load images with a blur-up placeholder effect using Intersection Observer and CSS transitions.
Best for: Image galleries
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 Compound Component Pattern
Build flexible compound components using React context for shared state between related parts.
Best for: Building flexible component libraries
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 Virtual List Component
Render large lists efficiently with windowing to only mount visible items in the viewport.
Best for: Rendering thousands of list items efficiently
React Portal Modal Component
Build an accessible modal dialog using React portals with focus trapping and keyboard handling.
Best for: Accessible modal dialogs with focus management
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 useReducer for Complex State
Manage complex component state with useReducer pattern including typed actions and middleware.
Best for: Shopping cart state management
React Optimistic Update Pattern
Implement optimistic UI updates that show changes immediately and rollback on server failure.
Best for: Instant UI feedback for server operations
React Responsive Breakpoint Hook
A useMediaQuery hook for responsive rendering with SSR-safe breakpoint detection.
Best for: Conditional rendering based on screen size
React Error Boundary Component
Build a reusable error boundary with retry, fallback UI, and error reporting integration.
Best for: Preventing full-page crashes from component errors
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
Context Selector Pattern
Avoid unnecessary re-renders with a context selector pattern that subscribes to specific state slices.
Best for: High-performance global state
Toast Notification System
Build a toast notification system with auto-dismiss, stacking, animations, and severity levels.
Best for: User feedback notifications
useMutation Hook for Side Effects
Handle mutations (POST/PUT/DELETE) with loading, error, reset, and optimistic update support.
Best for: Form submission handling
Accessible Tabs Component
Build an accessible tabs component with keyboard navigation, ARIA attributes, and focus management.
Best for: Tab navigation interfaces
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
Suspense Data Fetching Pattern
Use React Suspense for data fetching with resource caching, error boundaries, and streaming SSR.
Best for: Suspense-first data loading
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
Search with Text Highlighting
Build a search component that highlights matching text within results using safe HTML rendering.
Best for: Search results display
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
Optimistic List with Rollback
A list component that immediately reflects mutations and rolls back on server error.
Best for: Todo lists
Controlled Form Component
A reusable controlled form pattern with field-level validation and submission handling.
Best for: Login forms
Skeleton Loader Component
Animated skeleton placeholder component with configurable shapes for loading states.
Best for: Content loading states
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
Responsive Image Component
Image component with lazy loading, blur placeholder, error fallback, and srcset support.
Best for: Image galleries
Accordion Component
Accessible accordion component with keyboard navigation and animated expand/collapse.
Best for: FAQ sections
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
Command Palette Component
Keyboard-driven command palette with fuzzy search, keyboard navigation, and grouping.
Best for: App navigation
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
Sortable Data Table Component
Reusable data table with column sorting, type-safe accessors, and sort direction indicators.
Best for: Admin dashboards
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
Portal Dropdown Component
Dropdown menu rendered via Portal to avoid overflow clipping, with click-outside dismiss.
Best for: Navigation menus
usePrefetch Hook
Prefetches data or resources when the user hovers over an element to reduce perceived latency.
Best for: Route prefetching
Dynamic Breadcrumb Component
Generates breadcrumb navigation automatically from the current URL path segments.
Best for: Site navigation
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
Masonry Grid Component
CSS-based masonry layout component with configurable columns and responsive breakpoints.
Best for: Image galleries
useDebouncedCallback Hook
Returns a debounced version of a callback that delays execution until the pause in calls.
Best for: Search input debouncing
Error Boundary with Fallback UI
Error boundary class component with customizable fallback UI, retry button, and error reporting.
Best for: Graceful error recovery
useScreenWakeLock Hook
Prevents the screen from turning off using the Screen Wake Lock API.
Best for: Video playback
Conditional Wrapper Component
Utility component that conditionally wraps children in a parent element or renders them directly.
Best for: Optional link wrapping
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
Portal Tooltip Component
Accessible tooltip rendered via Portal with automatic positioning and arrow indicator.
Best for: Icon button labels
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
Context Provider Factory
Utility function that creates a typed React Context with a Provider and a custom hook in one call.
Best for: Creating typed contexts
usePersistentState Hook
Like useState but persists to localStorage with JSON serialization and SSR safety.
Best for: Persisting user preferences
Virtual Scroll List
Virtualized list that only renders visible items for large datasets with fixed row height.
Best for: Large data lists
useIsomorphicLayoutEffect Hook
Safely uses useLayoutEffect on client and useEffect on server to avoid SSR warnings.
Best for: DOM measurement before paint