typescriptintermediate
usePrefetch Hook
Prefetches data or resources when the user hovers over an element to reduce perceived latency.
typescriptPress ⌘/Ctrl + Shift + C to copy
import { useRef, useCallback, MouseEvent } from 'react';
const prefetchCache = new Set<string>();
export function usePrefetch(fetchFn: () => Promise<unknown>) {
const hasTriggered = useRef(false);
const onMouseEnter = useCallback((e: MouseEvent) => {
const key = (e.currentTarget as HTMLElement).dataset.prefetchKey || '';
if (hasTriggered.current || prefetchCache.has(key)) return;
hasTriggered.current = true;
prefetchCache.add(key);
fetchFn().catch(() => {
prefetchCache.delete(key);
hasTriggered.current = false;
});
}, [fetchFn]);
return { onMouseEnter };
}
// Usage:
// const prefetch = usePrefetch(() => fetch('/api/user/123'));
// <div {...prefetch} data-prefetch-key="user-123">Hover me</div>Use Cases
- Route prefetching
- Data prefetching on hover
Tags
Related Snippets
Similar patterns you can reuse in the same workflow.
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
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
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
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