typescriptintermediate
useIntersectionObserver Hook
Track element visibility with the Intersection Observer API for lazy loading and scroll animations.
typescriptPress ⌘/Ctrl + Shift + C to copy
import { useEffect, useRef, useState } from 'react';
export function useIntersectionObserver(
options: IntersectionObserverInit = {}
) {
const ref = useRef<HTMLElement>(null);
const [entry, setEntry] = useState<IntersectionObserverEntry | null>(null);
useEffect(() => {
const node = ref.current;
if (!node) return;
const observer = new IntersectionObserver(
([e]) => setEntry(e),
{ threshold: 0.1, ...options }
);
observer.observe(node);
return () => observer.disconnect();
}, [options.threshold, options.root, options.rootMargin]);
return { ref, entry, isVisible: entry?.isIntersecting ?? false };
}Use Cases
- Lazy loading images
- Infinite scroll triggers
- Scroll-based animations
Tags
Related Snippets
Similar patterns you can reuse in the same workflow.
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
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