UseIntersectionObserver
guarahooks/use-intersection-observerFreeHook
Observes when an element intersects the viewport or a root element.
Live preview
live · rendered by the registry
Rendered by guarahooks on their own page — this is the component running, not a screenshot of it.Install it
npx shadcn@latest add https://guarahooks.com/r/use-intersection-observer.jsonSource
1'use client';23import { useCallback, useEffect, useRef, useState } from 'react';45interface UseIntersectionObserverOptions extends IntersectionObserverInit {}67interface UseIntersectionObserverReturn<T extends Element = Element> {8 ref: (node: T | null) => void;9 entry: IntersectionObserverEntry | null;10 isIntersecting: boolean;11}1213export function useIntersectionObserver<T extends Element = Element>(14 options: UseIntersectionObserverOptions = {},15): UseIntersectionObserverReturn<T> {16 const [entry, setEntry] = useState<IntersectionObserverEntry | null>(null);17 const observerRef = useRef<IntersectionObserver | null>(null);1819 const ref = useCallback(20 (node: T | null) => {21 if (observerRef.current) {22 observerRef.current.disconnect();23 observerRef.current = null;24 }2526 if (node) {27 observerRef.current = new IntersectionObserver(([entry]) => {28 setEntry(entry);29 }, options);3031 observerRef.current.observe(node);32 } else {33 setEntry(null);34 }35 },36 [options],37 );3839 useEffect(() => {40 return () => {41 observerRef.current?.disconnect();42 };43 }, []);4445 const isIntersecting = entry?.isIntersecting ?? false;4647 return { ref, entry, isIntersecting };48}
Files it writes
More from guarahooks
All 100 items| Component | Registry | Kind | Access | Installs | Command |
|---|---|---|---|---|---|
| UseAbortControlleruse-abort-controller | guarahooks | Hooks | Free | no deps | |
| UseArrayStateuse-array-state | guarahooks | Hooks | Free | no deps | |
| UseAxiosuse-axios | guarahooks | Hooks | Free | no deps | |
| UseBatteryStatususe-battery-status | guarahooks | Hooks | Free | no deps | |
| UseBetterAuthuse-better-auth | guarahooks | Hooks | Free | no deps | |
| UseClickOutsideuse-click-outside | guarahooks | Hooks | Free | no deps | |
| UseConfirmuse-confirm | guarahooks | Hooks | Free | no deps | |
| UseCookieuse-cookie | guarahooks | Hooks | Free | no deps |
