useIntersectionObserver Hook
Track element visibility with the Intersection Observer API for lazy loading and scroll animations.
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.
Infinite Scroll with Intersection Observer
Load more items as the user scrolls using IntersectionObserver. No external libraries required.
useFetch — Generic Data Fetching Hook
Custom React hook for data fetching with loading, error, and refetch states using the Fetch API.
useDebounce — Debounced Value Hook
Debounce any rapidly-changing value with a configurable delay. Useful for search inputs and resize handlers.
useLocalStorage — Persistent State Hook
Sync React state with localStorage including SSR safety, JSON serialization, and cross-tab updates.