⚛️

React

Reusable React hooks, components, and patterns for modern frontend development.

100 snippets

Showing 100 of 100 snippets

typescriptintermediate

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

#hooks#fetch
typescriptbeginner

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

#hooks#debounce
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
typescriptbeginner

useClickOutside — Outside Click Detection

Detect clicks outside a referenced element to close dropdowns, modals, and popover menus.

Best for: Dropdown menus

#hooks#click-outside
typescriptbeginner

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

#hooks#responsive
typescriptintermediate

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

#error-boundary#error-handling
typescriptintermediate

Portal-Based Modal Component

Accessible modal component using React portals with focus trapping, Escape key close, and backdrop click.

Best for: Confirmation dialogs

#modal#portal
typescriptintermediate

Infinite Scroll with Intersection Observer

Load more items as the user scrolls using IntersectionObserver. No external libraries required.

Best for: Feed pagination

#infinite-scroll#intersection-observer
typescriptadvanced

Optimistic Update Pattern

Apply UI changes immediately before server confirmation with automatic rollback on failure.

Best for: Like/upvote buttons

#optimistic-update#state
typescriptadvanced

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

#context#reducer
typescriptintermediate

useIntersectionObserver Hook

Track element visibility with the Intersection Observer API for lazy loading and scroll animations.

Best for: Lazy loading images

#hooks#intersection-observer
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
typescriptbeginner

useWindowSize Hook

Track browser window dimensions with debounced resize handling for responsive component logic.

Best for: Responsive layouts

#hooks#responsive
typescriptbeginner

useCopyToClipboard Hook

Copy text to clipboard with success state and automatic reset timer using the Clipboard API.

Best for: Copy code snippets

#hooks#clipboard
typescriptadvanced

Virtualized List Component

Render large lists efficiently by only rendering visible items with calculated scroll positioning.

Best for: Rendering 10k+ item lists

#virtualization#performance
typescriptintermediate

Drag & Drop Sortable List

Reorder list items with native HTML drag and drop events — no external library required.

Best for: Task board reordering

#drag-drop#sortable
typescriptadvanced

Compound Component Pattern

Build flexible compound components using React Context for implicit parent-child communication.

Best for: Accordion components

#patterns#compound-component
typescriptintermediate

Render Prop Pattern

Share stateful logic between components using the render prop pattern for maximum flexibility.

Best for: Mouse tracking

#patterns#render-prop
typescriptintermediate

useFormValidation Hook

Lightweight form validation hook with field-level errors, touched tracking, and submit handling.

Best for: Contact forms

#hooks#forms
typescriptbeginner

Image Lazy Load Component

Lazy load images with a blur-up placeholder effect using Intersection Observer and CSS transitions.

Best for: Image galleries

#images#lazy-loading
typescriptintermediate

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#hooks
typescriptadvanced

React Compound Component Pattern

Build flexible compound components using React context for shared state between related parts.

Best for: Building flexible component libraries

#react#patterns
typescriptintermediate

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#forms
typescriptadvanced

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#virtualization
typescriptintermediate

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#portal
typescriptintermediate

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#hooks
typescriptintermediate

React useReducer for Complex State

Manage complex component state with useReducer pattern including typed actions and middleware.

Best for: Shopping cart state management

#react#useReducer
typescriptadvanced

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#optimistic-ui
typescriptbeginner

React Responsive Breakpoint Hook

A useMediaQuery hook for responsive rendering with SSR-safe breakpoint detection.

Best for: Conditional rendering based on screen size

#react#responsive
typescriptintermediate

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

#react#error-boundary
typescriptintermediate

useThrottle Hook for Rate Limiting

Throttle rapidly-firing values like scroll or resize events with a configurable delay hook.

Best for: Scroll position tracking

#react#hooks
typescriptintermediate

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

#react#hooks
typescriptbeginner

useKeyboardShortcut Hook

Register global keyboard shortcuts with modifier keys, preventing defaults, and cleanup on unmount.

Best for: Command palette shortcuts

#react#hooks
typescriptadvanced

Context Selector Pattern

Avoid unnecessary re-renders with a context selector pattern that subscribes to specific state slices.

Best for: High-performance global state

#react#context
typescriptintermediate

Toast Notification System

Build a toast notification system with auto-dismiss, stacking, animations, and severity levels.

Best for: User feedback notifications

#react#toast
typescriptintermediate

useMutation Hook for Side Effects

Handle mutations (POST/PUT/DELETE) with loading, error, reset, and optimistic update support.

Best for: Form submission handling

#react#hooks
typescriptintermediate

Accessible Tabs Component

Build an accessible tabs component with keyboard navigation, ARIA attributes, and focus management.

Best for: Tab navigation interfaces

#react#accessibility
typescriptadvanced

useInfiniteQuery Hook

Implement infinite scrolling with cursor-based pagination, loading states, and intersection observer.

Best for: Infinite scroll feeds

#react#hooks
typescriptbeginner

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

#react#hooks
typescriptadvanced

Suspense Data Fetching Pattern

Use React Suspense for data fetching with resource caching, error boundaries, and streaming SSR.

Best for: Suspense-first data loading

#react#suspense
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
typescriptbeginner

Search with Text Highlighting

Build a search component that highlights matching text within results using safe HTML rendering.

Best for: Search results display

#react#search
typescriptintermediate

useInterval Hook

Declarative setInterval hook that handles cleanup and dynamic delay changes safely.

Best for: Polling APIs

#hooks#timer
typescriptbeginner

useTimeout Hook

Declarative setTimeout hook with automatic cleanup and reset capabilities.

Best for: Auto-dismiss notifications

#hooks#timer
typescriptbeginner

useToggle Hook

Simple boolean toggle hook with set, toggle, on, and off functions.

Best for: Modal open/close state

#hooks#state
typescriptbeginner

useHover Hook

Tracks whether an element is being hovered using mouse enter/leave events with a ref.

Best for: Tooltip triggers

#hooks#mouse
typescriptbeginner

useOnlineStatus Hook

Tracks browser online/offline status and re-renders when connectivity changes.

Best for: Offline-first apps

#hooks#network
typescriptintermediate

useScrollPosition Hook

Tracks window scroll position with throttling for performance-sensitive scroll effects.

Best for: Sticky headers

#hooks#scroll
typescriptbeginner

useLockBodyScroll Hook

Locks body scroll when active, commonly used with modals and overlays to prevent background scrolling.

Best for: Modal dialogs

#hooks#scroll
typescriptbeginner

useDocumentTitle Hook

Dynamically updates the document title and restores it on unmount.

Best for: Page title updates

#hooks#document
typescriptadvanced

useFocusTrap Hook

Traps keyboard focus within a container for accessible modals and dialogs.

Best for: Accessible modals

#hooks#a11y
typescriptintermediate

useIdleDetection Hook

Detects user inactivity after a configurable timeout by monitoring mouse, keyboard, and touch events.

Best for: Auto-logout

#hooks#idle
typescriptadvanced

Optimistic List with Rollback

A list component that immediately reflects mutations and rolls back on server error.

Best for: Todo lists

#optimistic-ui#list
typescriptintermediate

Controlled Form Component

A reusable controlled form pattern with field-level validation and submission handling.

Best for: Login forms

#form#controlled
typescriptbeginner

Skeleton Loader Component

Animated skeleton placeholder component with configurable shapes for loading states.

Best for: Content loading states

#skeleton#loading
typescriptintermediate

useStepWizard Hook

Multi-step wizard hook that manages step navigation, validation gates, and completion state.

Best for: Onboarding flows

#hooks#wizard
typescriptbeginner

useClipboard Hook (Advanced)

Clipboard hook with read, write, and auto-reset of the copied state after a timeout.

Best for: Copy-to-clipboard buttons

#hooks#clipboard
typescriptintermediate

Responsive Image Component

Image component with lazy loading, blur placeholder, error fallback, and srcset support.

Best for: Image galleries

#image#responsive
typescriptintermediate

Accordion Component

Accessible accordion component with keyboard navigation and animated expand/collapse.

Best for: FAQ sections

#accordion#a11y
typescriptadvanced

useFetch with Cache Hook

Data fetching hook with built-in cache, loading, error states, and automatic revalidation.

Best for: API data fetching

#hooks#fetch
typescriptintermediate

useDarkMode Hook

Dark mode hook that syncs with system preferences and persists user choice to localStorage.

Best for: Theme switching

#hooks#dark-mode
typescriptintermediate

usePermission Hook

Queries and tracks browser permission state for features like notifications, camera, and geolocation.

Best for: Permission-gated features

#hooks#permissions
typescriptadvanced

useMutationObserver Hook

Wraps the MutationObserver API in a React hook to observe DOM changes on a target element.

Best for: Third-party widget monitoring

#hooks#dom
typescriptintermediate

useCountdown Hook

Countdown timer hook with start, pause, reset, and formatted time remaining output.

Best for: OTP expiry timers

#hooks#countdown
typescriptadvanced

Command Palette Component

Keyboard-driven command palette with fuzzy search, keyboard navigation, and grouping.

Best for: App navigation

#command-palette#keyboard
typescriptintermediate

useResizeObserver Hook

Tracks element dimensions using ResizeObserver with debounced updates.

Best for: Responsive layouts

#hooks#resize
typescriptintermediate

useGeolocation Hook

Accesses browser geolocation API with loading, error states, and watch mode support.

Best for: Location-based features

#hooks#geolocation
typescriptintermediate

useLongPress Hook

Detects long press gestures on touch and mouse devices with configurable threshold.

Best for: Context menus

#hooks#gesture
typescriptintermediate

useSearchParamsState Hook

Syncs component state with URL search parameters for shareable filter/sort states.

Best for: Filter state persistence

#hooks#url
typescriptadvanced

useWebSocket Hook

WebSocket hook with auto-reconnect, message queuing, and connection state tracking.

Best for: Chat applications

#hooks#websocket
typescriptintermediate

Infinite Scroll Hook v2

Intersection Observer-based infinite scroll with loading, error, and hasMore states.

Best for: Feed-style content

#hooks#infinite-scroll
typescriptadvanced

useHistoryState Hook

State hook that maintains full history with undo, redo, and time-travel capabilities.

Best for: Drawing apps

#hooks#undo
typescriptadvanced

useMediaRecorder Hook

Wraps the MediaRecorder API for audio/video recording with start, stop, and blob output.

Best for: Voice memos

#hooks#media
typescriptadvanced

useSelectionRange Hook

Tracks user text selection within a container, returning selected text and range coordinates.

Best for: Text annotation tools

#hooks#selection
typescriptintermediate

Sortable Data Table Component

Reusable data table with column sorting, type-safe accessors, and sort direction indicators.

Best for: Admin dashboards

#table#sorting
typescriptadvanced

useIndexedDB Hook

Simple IndexedDB wrapper hook for persistent client-side storage with get, set, and delete.

Best for: Offline data storage

#hooks#indexeddb
typescriptadvanced

useTransitionGroup Hook

Manages enter/exit animations for list items with staggered transitions.

Best for: Animated list additions/removals

#hooks#animation
typescriptintermediate

useSpeechSynthesis Hook

Text-to-speech hook using the Web Speech API with voice selection, rate, and pitch control.

Best for: Accessibility features

#hooks#speech
typescriptintermediate

useNetworkSpeed Hook

Monitors the Network Information API to report connection type, downlink speed, and effective type.

Best for: Adaptive media quality

#hooks#network
typescriptintermediate

Portal Dropdown Component

Dropdown menu rendered via Portal to avoid overflow clipping, with click-outside dismiss.

Best for: Navigation menus

#portal#dropdown
typescriptintermediate

usePrefetch Hook

Prefetches data or resources when the user hovers over an element to reduce perceived latency.

Best for: Route prefetching

#hooks#prefetch
typescriptbeginner

Dynamic Breadcrumb Component

Generates breadcrumb navigation automatically from the current URL path segments.

Best for: Site navigation

#breadcrumb#navigation
typescriptbeginner

useAbortController Hook

Creates and manages AbortController instances for cancelling fetch requests on unmount.

Best for: Cancelling stale requests

#hooks#abort
typescriptbeginner

usePageVisibility Hook

Detects when the page is hidden or visible using the Page Visibility API.

Best for: Pausing animations

#hooks#visibility
typescriptintermediate

Masonry Grid Component

CSS-based masonry layout component with configurable columns and responsive breakpoints.

Best for: Image galleries

#masonry#grid
typescriptbeginner

useDebouncedCallback Hook

Returns a debounced version of a callback that delays execution until the pause in calls.

Best for: Search input debouncing

#hooks#debounce
typescriptintermediate

Error Boundary with Fallback UI

Error boundary class component with customizable fallback UI, retry button, and error reporting.

Best for: Graceful error recovery

#error-boundary#error-handling
typescriptintermediate

useScreenWakeLock Hook

Prevents the screen from turning off using the Screen Wake Lock API.

Best for: Video playback

#hooks#wake-lock
typescriptbeginner

Conditional Wrapper Component

Utility component that conditionally wraps children in a parent element or renders them directly.

Best for: Optional link wrapping

#utility#wrapper
typescriptbeginner

useBreakpoints Hook

Returns the current Tailwind-style breakpoint based on window width for responsive logic.

Best for: Responsive component logic

#hooks#responsive
typescriptintermediate

useThrottledValue Hook

Throttles a rapidly changing value to update at most once per specified interval.

Best for: Scroll position tracking

#hooks#throttle
typescriptintermediate

Portal Tooltip Component

Accessible tooltip rendered via Portal with automatic positioning and arrow indicator.

Best for: Icon button labels

#tooltip#portal
typescriptadvanced

useStorageEvent Hook

Syncs state across browser tabs by listening to localStorage storage events.

Best for: Theme sync across tabs

#hooks#storage
typescriptbeginner

useFormDirty Hook

Tracks whether a form has unsaved changes and warns before page unload.

Best for: Form unsaved-changes warning

#hooks#form
typescriptintermediate

useFullscreen Hook

Toggle fullscreen mode on an element using the Fullscreen API with state tracking.

Best for: Video players

#hooks#fullscreen
typescriptbeginner

useClickAway Hook

Fires a callback when a click is detected outside the referenced element.

Best for: Dropdown close on outside click

#hooks#click-outside
typescriptadvanced

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

#context#provider
typescriptbeginner

usePersistentState Hook

Like useState but persists to localStorage with JSON serialization and SSR safety.

Best for: Persisting user preferences

#hooks#localstorage
typescriptadvanced

Virtual Scroll List

Virtualized list that only renders visible items for large datasets with fixed row height.

Best for: Large data lists

#virtualization#list
typescriptbeginner

useIsomorphicLayoutEffect Hook

Safely uses useLayoutEffect on client and useEffect on server to avoid SSR warnings.

Best for: DOM measurement before paint

#hooks#ssr