Hooks
use-intersection-observer
11/4/2025, 11:04:14 AM modified by MarvinA hook to check if an element is intersecting with the viewport
Use Intersection Observer
The useIntersectionObserver hook is a hook that checks if an element is intersecting with the viewport.
Installation
Loading...
Preview
Not Intersecting
'use client';import { useEffect, useRef, useState } from 'react';export const useIntersectionObserver = <T extends Element = HTMLElement>(options: IntersectionObserverInit = {}) => { const [isIntersecting, setIsIntersecting] = useState(false); const [entry, setEntry] = useState<IntersectionObserverEntry | null>(null); const ref = useRef<T>(null); useEffect(() => { const element = ref.current; if (!element) return; // 检查浏览器支持 if (!window.IntersectionObserver) { console.warn('IntersectionObserver is not supported in this browser'); return; } const observer = new IntersectionObserver( ([entry]) => { setIsIntersecting(entry.isIntersecting); setEntry(entry); }, { root: options.root, rootMargin: options.rootMargin, threshold: options.threshold }, ); observer.observe(element); return () => { observer.unobserve(element); observer.disconnect(); }; }, [options.root, options.rootMargin, options.threshold]); return { ref, isIntersecting, entry };};'use client';import { useIntersectionObserver } from './index';export const Demo = () => { const { ref, isIntersecting } = useIntersectionObserver<HTMLDivElement>(); return ( <div className="h-[100px] overflow-y-scroll border"> <span className="sticky top-0 text-xs">{isIntersecting ? 'Intersecting' : 'Not Intersecting'}</span> <div ref={ref} className="size-[20px] bg-red-500 my-[100px]"></div> </div> );};Git Commit History(3 commits)
feat: use-fcm
Marvin
11月4日 11:04
ae830ba8refactor: 优化目录
Marvin
10月29日 15:55
0c4142fbfeat: 初始化git仓库
Marvin
10月29日 13:35
1300e546