今日已更新 412 条资讯 | 累计 19972 条内容
关于我们

React useIntersectionObserver Hook: Lazy Load & Detect Visibility (2026)

reactuse.com 2026年06月30日 17:21 1 次阅读 来源:Dev.to

React useIntersectionObserver Hook: Lazy Load & Detect Visibility (2026) You want to load an image only when it scrolls near the viewport. Or fire an analytics event the first time a card is actually seen . Or trigger "load more" when the user reaches the bottom of a list. Every one of these is the same question — is this element on screen yet? — and for years the answer was a scroll listener that fired hundreds of times a second, re-read getBoundingClientRect() on each tick, and still managed to miss the edge cases. IntersectionObserver is the browser API that answers that question correctly, asynchronously, and off the main thread. useIntersectionObserver is the hook that wires it into React without the useEffect / useRef /cleanup boilerplate — and without the leak-on-unmount and stale-closure bugs the hand-rolled version always ships. This post covers the real @reactuses/core API, the three patterns you'll actually reach for, and how to tune threshold , rootMargin , and root . SSR-safe and typed. Why Not Just Use a Scroll Listener? The old way to know whether an element was visible looked like this: listen to scroll , and on every event measure the element against the viewport. useEffect (() => { function onScroll () { const rect = el . getBoundingClientRect (); if ( rect . top < window . innerHeight ) { setVisible ( true ); } } window . addEventListener ( ' scroll ' , onScroll ); return () => window . removeEventListener ( ' scroll ' , onScroll ); }, []); This has two problems baked in. First, scroll fires on the main thread, dozens of times per second, and getBoundingClientRect() forces a synchronous layout each time — that's exactly the recipe for janky scrolling. Second, it only catches elements crossing the viewport ; the moment your scroll happens inside a container, you're re-deriving geometry by hand. IntersectionObserver flips the model. You hand the browser a target and a threshold, and it tells you — asynchronously, batched, off the scroll path — when

本文内容来源于互联网,版权归原作者所有
查看原文