Most people meet IntersectionObserver through lazy-loaded images, and stop there. But the question it answers, "is this element on screen, or close to it?", shows up all over a frontend: infinite lists, analytics, navigation, sticky UI, media.
I built six of these patterns from scratch in React, with tests, and each one had its own trap. This post is the result: one small hook, six patterns, the bug that bit me in each, and how to test all of it without a browser. These are also some of the most common live-coding tasks for frontend roles, so they're worth knowing cold.
To be honest, in the SaaS products I've worked on I never needed IntersectionObserver beyond the basics, so these patterns were a gap for me. I wrote this post to close it and share what I learned.
Why not a scroll listener?
The old way was window.addEventListener('scroll', ...) plus getBoundingClientRect() on every element you care about. That runs on the main thread on every scroll event and forces layout each time you read a rect. With fifty cards on a page, it adds up.
IntersectionObserver flips it around. You tell the browser which elements to watch and where the "trigger zone" is, and the browser calls you only when something crosses it. It runs off the scroll path, and it batches: one callback can bring several entries.
Two options do most of the work:
-
rootMargin: where the trigger zone is.'0px 0px 200px 0px'extends the viewport 200px down, so things fire before they are visible. Negative values shrink it:'0px 0px -50% 0px'is the top half of the screen. Every value needs a unit,'0 0 200px 0'is invalid. -
threshold: how much of the element must be inside it.0means "any pixel",0.5means "half". It can be an array of any values between 0 and 1, like[0, 0.7, 1]: you get a call each time the visible share crosses one of them, in either direction.
Three threshold traps worth knowing before the patterns:
-
It's a share of the element, not of the screen. A section taller than the viewport can never be 100% visible, so
threshold: 1never fires for it. Use a lower value, or shrink the root withrootMargininstead. -
An array is a set of checkpoints, not a stream. Nothing fires between the points, and a fast scroll can jump over several in one frame: going from 10% to 90% visible gives one call, not two. Read
entry.intersectionRatiofor the actual value instead of counting calls. -
Calls come on the way out too. With
threshold: 0.5, dropping from 60% to 40% visible also fires, andisIntersectingis stilltruebecause part of the element is on screen. Pattern 6 below depends on getting this right.
The base: useInView
Everything below starts from this hook:
import { useEffect, useState } from 'react';
export function useInView({ rootMargin = '0px', threshold = 0, once = false } = {}) {
const [element, setElement] = useState(null);
const [inView, setInView] = useState(false);
useEffect(() => {
if (!element) return;
const observer = new IntersectionObserver(
([entry]) => {
if (entry.isIntersecting && once) {
setInView(true);
observer.disconnect();
} else if (!once) {
setInView(entry.isIntersecting);
}
},
{ rootMargin, threshold },
);
observer.observe(element);
return () => observer.disconnect();
}, [element, rootMargin, threshold, once]);
return [setElement, inView];
}
const [ref, inView] = useInView({ threshold: 0.5 });
return <div ref={ref}>{inView ? 'On screen' : 'Off screen'}</div>;
It looks small, but almost every line is there because of a bug.
ref is a useState setter, not useRef. This is a callback ref: React calls setElement(node) when the element mounts and setElement(null) when it unmounts. Because it's state, the effect re-runs when the element appears. With useRef, an element that renders later (after a loading state, behind a condition) is never observed, because changing ref.current doesn't re-run anything. Callback refs aren't new, they've been in React for years; React 19 only added the option to return a cleanup from them.
Options go into the dependencies as primitives. Callers write useInView({ rootMargin: '100px' }), so the options object is new on every render. If the effect depended on the object, every render would tear down the observer and create a new one. Strings and numbers compare by value, so [rootMargin, threshold] is stable. If you accept threshold as an array, turn it into a string for the dependency (threshold.join(',')) and parse it back inside the effect.
observe() takes an element, not a ref. observer.observe(ref) with a useRef object throws TypeError: parameter 1 is not of type 'Element' in a browser. Forgetting observe() altogether is worse: nothing throws, the observer simply watches nothing.
disconnect() in the cleanup. Otherwise the observer outlives the component and keeps calling setState on it.
Pattern 1: lazy images

Images load just before they scroll into view. The grey boxes are placeholders.
function LazyImage({ src, alt }) {
const [ref, inView] = useInView({ rootMargin: '0px 0px 200px 0px', once: true });
const [loaded, setLoaded] = useState(false);
return (
<img
ref={ref}
src={inView ? src : undefined}
alt={alt}
width={200}
height={200}
data-loaded={loaded || undefined}
onLoad={() => setLoaded(true)}
/>
);
}
Render every <img> from the start with its size, so the layout doesn't jump, but without a src. When it gets within 200px of the screen, give it the real src. once: true stops watching after that: a loaded image stays loaded.
Two states, not one: inView means "we set the src", loaded means "the browser finished downloading". The second is what drives a fade-in or hides the placeholder.
The trap: threshold: 1. It's easy to copy from an example, and it means "call me when the element is 100% visible". For lazy loading you want the opposite: start before it's visible. That's rootMargin, not threshold.
If you share one observer for the whole gallery instead of one per image, you'll identify images with data-index and read entry.target.dataset.index. Remember that dataset values are always strings ("3", not 3), and that data-index in JSX is dataset.index in JavaScript. A mismatch gives you undefined, and nothing loads, with no error.
And for a plain list of images, start with <img loading="lazy">. It needs no JavaScript. Reach for the observer when you need control: the distance, a placeholder, a fade-in.
Pattern 2: infinite scroll

The next page loads when the sentinel after the last item gets close to the screen.
Put an empty "sentinel" element after the last item. When it comes into view, load the next page.
export function InfiniteList({ loadPage }) {
const [items, setItems] = useState([]);
const [hasMore, setHasMore] = useState(true);
const [sentinel, setSentinel] = useState(null);
// The observer callback is created once, so it reads live values from a ref, not from state.
const live = useRef({ page: 1, inFlight: false, inView: false, hasMore: true });
useEffect(() => {
if (!sentinel) return;
const s = live.current;
function loadNext() {
if (s.inFlight || !s.hasMore) return;
s.inFlight = true;
loadPage(s.page).then((res) => {
s.inFlight = false;
s.page += 1;
s.hasMore = res.hasMore;
setItems((prev) => [...prev, ...res.items]);
setHasMore(res.hasMore);
if (s.inView) loadNext(); // the page was too short to push the sentinel away
});
}
const observer = new IntersectionObserver(
([entry]) => {
s.inView = entry.isIntersecting;
if (entry.isIntersecting) loadNext();
},
{ rootMargin: '0px 0px 300px 0px' },
);
observer.observe(sentinel);
return () => observer.disconnect();
}, [sentinel, loadPage]);
return (
<>
<ul>{items.map((item) => <li key={item}>{item}</li>)}</ul>
{hasMore && <div ref={setSentinel} />}
</>
);
}
The live ref holds what the callback reads: the next page, whether a request is in flight, whether the sentinel is on screen. State is only for rendering. The inFlight flag stops a second request while the first one is still running.
The trap: a short page. The observer reports changes. The first page loads, but it's only three items tall, so the sentinel never leaves the screen. It never leaves, so it never "enters" again, and the list silently stops at page one. The fix is the line marked with a comment: after each response, if the sentinel is still in view, load again.
Make it better: a real list needs a loading indicator and an error state. When a request fails, stop auto-loading (otherwise a sentinel on screen retries in a loop) and show a Retry button.
Pattern 3: impressions

A card turns green after half of it was on screen for one second. Cards scrolled past quickly are not counted.
Analytics wants to know when a product card was seen: at least half of it on screen, for a full second. Scrolling fast past it doesn't count. It's counted once.
export function useImpression(onImpression, { threshold = 0.5, delay = 1000 } = {}) {
const [el, setEl] = useState(null);
const callbackRef = useRef(onImpression);
useEffect(() => {
callbackRef.current = onImpression; // always call the latest callback
});
useEffect(() => {
if (!el) return;
let timer = null;
const observer = new IntersectionObserver(
([entry]) => {
if (entry.isIntersecting) {
if (timer) return; // already counting
timer = setTimeout(() => {
observer.disconnect(); // once is enough
callbackRef.current();
}, delay);
} else {
clearTimeout(timer); // left too early: start from zero next time
timer = null;
}
},
{ threshold },
);
observer.observe(el);
return () => {
clearTimeout(timer);
observer.disconnect();
};
}, [el, threshold, delay]);
return setEl;
}
Trap 1: the inline callback. Callers write useImpression(() => track(product.id)), so it's a new function on every render. Putting it in the dependencies would restart the observer, and the one-second count, on every render. Leaving it out calls a stale callback with old props. Instead, a ref always holds the latest callback, and the timer calls callbackRef.current() when it fires.
Trap 2: unmount with a pending count. The card can disappear (a filter, a route change) while the timer is running. Without clearTimeout in the cleanup, the impression is reported for a card that's gone.
Also notice if (timer) return: a second "visible" entry must not restart the count.
Make it better: a card on screen in a background tab isn't seen either. See "On screen, but in a hidden tab" below.
Pattern 4: scroll-spy

The sidebar follows the section in the top half of the screen.
The "On this page" sidebar on docs sites highlights the section you're reading.
export function useScrollSpy(ids, { rootMargin = '0px 0px -50% 0px' } = {}) {
const [active, setActive] = useState(null);
const key = ids.join(',');
useEffect(() => {
const list = key.split(',');
const visible = new Set();
const observer = new IntersectionObserver(
(entries) => {
entries.forEach((e) =>
e.isIntersecting ? visible.add(e.target.id) : visible.delete(e.target.id),
);
const first = list.find((id) => visible.has(id));
if (first) setActive(first);
},
{ rootMargin },
);
list.forEach((id) => {
const el = document.getElementById(id);
if (el) observer.observe(el);
});
return () => observer.disconnect();
}, [key, rootMargin]);
return active;
}
The default rootMargin shrinks the viewport to its top half, so a section counts as "visible" when it's in the upper part of the screen. Several sections can be there at once; the active one is the first in document order. When none is visible (a gap between sections), the last active one stays, so the sidebar doesn't blink.
Trap 1: one callback, many entries. In the impressions hook I took the last entry, because there was one element. Here a fast scroll brings several sections in one callback, some entering, some leaving. Taking the last one picks the wrong section. Process every entry, keep a set of what's visible across callbacks, then pick.
Trap 2: an array in the dependencies. useScrollSpy(['intro', 'setup', 'faq']) is a new array on every render. ids.join(',') turns it into a string: same ids, same string, no new observer. New sections still get picked up, because the string changes.
Make it better: put the active id into the URL hash, so readers can copy a link to where they are. Use history.replaceState, not pushState, or the Back button walks through every section they scrolled past. And skip it until something is active: I got #null in the URL that way, and only the demo page showed it.
Pattern 5: sticky header shadow

Each section header gets a shadow while it is stuck, and the next one pushes it out.
position: sticky can't tell you when it's actually stuck, so you can't add a shadow with CSS alone. Put a 1px sentinel right above the header and watch it: once the sentinel has scrolled out over the top edge, the header is stuck.
export function useStuck({ offset = 0 } = {}) {
const [el, setEl] = useState(null);
const [stuck, setStuck] = useState(false);
useEffect(() => {
if (!el) return;
const observer = new IntersectionObserver(
([entry]) => {
const rootTop = entry.rootBounds?.top ?? 0;
setStuck(!entry.isIntersecting && entry.boundingClientRect.top < rootTop);
},
{ threshold: 0, rootMargin: `${-offset}px 0px 0px 0px` },
);
observer.observe(el);
return () => observer.disconnect();
}, [el, offset]);
return [setEl, stuck];
}
const [sentinelRef, stuck] = useStuck();
return (
<>
<div ref={sentinelRef} />
<header style={{ position: 'sticky', top: 0, boxShadow: stuck ? '0 2px 8px #0003' : 'none' }}>…</header>
</>
);
It works the same for several section headers, like the letters in a contacts list. Give each section its own sentinel and its own useStuck(). Put each sticky header inside its section: a sticky element never leaves its parent, so when a section ends, its header scrolls away and the next one takes its place. No extra JavaScript for the push.
offset is for a header that sticks below another fixed bar (top: 64px): the negative rootMargin moves the top edge of the trigger zone down by the same amount.
Make it better: add an onChange(stuck) callback for things outside React state, like analytics or a compact header mode. Call it only when the value actually changes, and keep the latest callback in a ref, as in the impressions hook.
The trap: "not visible" has two meanings. The sentinel is not intersecting when it scrolled out over the top (stuck), but also when it's still below the screen and the reader hasn't reached the header yet (not stuck). With !isIntersecting alone, a page that opens at the top shows a shadow on a header far down the page. Compare positions: boundingClientRect is where the sentinel is, rootBounds is the trigger zone after rootMargin. Above means stuck. (rootBounds can be null when the page runs in a cross-origin iframe, hence the ?? 0.)
Pattern 6: play video only while it's on screen

Three videos, one hook each: only the video on screen plays. The event log on the right shows each play and pause.
A muted looping video should play while it's on screen and pause when it leaves, to save CPU, battery and data. Unlike impressions, this goes both ways and never stops.
export function useAutoplay({ threshold = 0.5 } = {}) {
const [video, setVideo] = useState(null);
useEffect(() => {
if (!video) return;
const observer = new IntersectionObserver(
([entry]) => {
const inView = entry.isIntersecting && entry.intersectionRatio >= threshold;
if (inView && video.paused) {
video.play().catch(() => {}); // autoplay can be blocked
} else if (!inView && !video.paused) {
video.pause();
}
},
{ threshold },
);
observer.observe(video);
return () => observer.disconnect();
}, [video, threshold]);
return setVideo;
}
Trap 1: isIntersecting is not "visible enough". With threshold: 0.5 the browser also calls you when the video goes down through 50%, from 60% to 40% visible. That entry still has isIntersecting: true, because part of it is on screen. Check intersectionRatio >= threshold as well.
Trap 2: play() returns a Promise. The browser rejects it when autoplay isn't allowed (NotAllowedError). Without the .catch, that's an unhandled rejection in your error tracker on every scroll.
Trap 3: calling play() or pause() at the wrong time. Calling pause() while play() is still starting gives you the classic AbortError: The play() request was interrupted by a call to pause(). Check video.paused first. And compute inView before branching: my first version had if (visible && paused) play; else if (!paused) pause, which pauses a visible video that's already playing.
Make it better: if the user paused the video with the controls, scrolling away and back shouldn't start it again. Listen to the play and pause events, but note they arrive later, after your call returns, so a "this is my pause" flag set around pause() won't work. Decide by position instead: the hook only pauses off-screen videos, so a pause while it's on screen came from the user. And if prefers-reduced-motion is set, don't autoplay at all.
The same idea pauses CSS animations (animation-play-state: paused), canvas loops (cancelAnimationFrame) or polling with setInterval when they're off screen.
On screen, but in a hidden tab
IntersectionObserver only knows geometry. When the user switches to another tab, minimizes the window or locks the phone, the element is still exactly where it was, so the observer stays silent. An impression timer keeps counting for nobody, and a video keeps decoding for nobody.
The Page Visibility API covers that gap: document.visibilityState is 'visible' or 'hidden', and the visibilitychange event on document fires on every switch. Treat it as a second signal and make one decision from both:
const update = () => {
const visible = inView && document.visibilityState !== 'hidden'
// impressions: start or cancel the timer
// video: play() or pause()
}
// call update() from the observer callback AND from visibilitychange
One function that both events call keeps the logic in one place: whoever changed the state, the answer is computed the same way.
The trap: it breaks "respect the user". In Pattern 6 a pause while the video is on screen means the user paused it. Pausing because the tab went hidden also happens on screen, and the pause event arrives later, so the hook decides the user did it and never resumes. Count a pause as the user's only when the tab is visible too.
Outside of observers the same event is useful for stopping a carousel's autoplay or a polling loop in a background tab, refetching data when the user comes back (that's how TanStack Query's refetchOnWindowFocus works), and sending analytics with navigator.sendBeacon on the switch to hidden, which is more reliable on mobile than unload.
Testing all of it in Vitest
jsdom has no IntersectionObserver, and no layout, so nothing would ever intersect anyway. A small mock that records what's observed, plus a helper that "scrolls" by calling the callback, covers every pattern above:
let observers = [];
class MockIntersectionObserver {
constructor(callback, options = {}) {
this.callback = callback;
this.options = options;
this.elements = new Set();
observers.push(this);
}
observe(el) {
// Be as strict as the browser, or observe(ref) passes in tests and throws in production.
if (!(el instanceof Element)) {
throw new TypeError("Failed to execute 'observe' on 'IntersectionObserver': parameter 1 is not of type 'Element'.");
}
this.elements.add(el);
}
unobserve(el) { this.elements.delete(el); }
disconnect() { this.elements.clear(); }
takeRecords() { return []; }
}
beforeEach(() => {
observers = [];
window.IntersectionObserver = MockIntersectionObserver;
});
// Pretend `ratio` of `el` is on screen.
function scroll(el, ratio, isIntersecting = ratio > 0) {
act(() => {
observers
.filter((o) => o.elements.has(el))
.forEach((o) => o.callback([{ target: el, isIntersecting, intersectionRatio: ratio }], o));
});
}
Then each trap becomes a test:
it('cancels the count when the card leaves early', () => {
render(<Card onImpression={onImpression} />);
scroll(card(), 0.6);
wait(500);
scroll(card(), 0);
wait(1000);
expect(onImpression).not.toHaveBeenCalled();
});
it('keeps one observer when the parent re-renders', () => {
const { rerender } = render(<Card onImpression={onImpression} />);
rerender(<Card onImpression={onImpression} />);
expect(observers).toHaveLength(1);
});
A few things I learned writing these:
- Make the test component pass options inline, exactly like real callers. Otherwise the "new object on every render" bug never shows up.
-
The real browser sends a first notification right after
observe(); the mock doesn't. That's fine for most tests, as long as you remember the mock only does what you tell it. -
Fake timers for anything with a delay.
vi.useFakeTimers()andvi.advanceTimersByTime(999)make "not before one second" a one-line assertion. -
Mock media like the browser behaves. jsdom can't play video, so replace
play(),pause()andpausedonHTMLMediaElement.prototype. Changepausedat once, and if you test the events too, fire them withsetTimeout, like a browser does. -
vi.fn()can hide an unhandled rejection. Ifplayis avi.fn()that returns a rejected Promise, Vitest subscribes to the result to record it, and the rejection counts as handled. My test for the missing.catchpassed when it shouldn't. Count calls with a separate spy and keepplaya plain function.
What this doesn't test: real layout and real scrolling. For that, a Playwright test that scrolls the page and checks what happened is worth one or two cases per pattern.
The observer family
IntersectionObserver has siblings with the same shape (new XObserver(callback), observe, disconnect), each for a different question:
-
ResizeObserver: did this element change size? Good for a "Show more" button that appears only when the text is actually cut off, or a chart that redraws when its container resizes. -
MutationObserver: did the DOM change? Good for reacting to adarkclass on<html>that another script toggles, or to content a third-party widget injects. It's for reacting and monitoring. It is not a security tool: by the time it reports an injected script, the script may already have run. For XSS, use output escaping, a Content Security Policy and Trusted Types. -
PerformanceObserver: what did the browser measure? It reports Largest Contentful Paint, long tasks and layout shifts as they happen, which is how real-user monitoring libraries collect Web Vitals.
Wrapping up
The six patterns share one shape: a callback ref, primitive options in the dependencies, a ref for anything a long-lived callback reads, and disconnect() in the cleanup. What differs is the question you ask in the callback: is it close, did it stay, which one is first, which side of the edge, who paused it.
Which of these patterns do you use, and in which flows? I'd love to hear about the trap that bit you.
Top comments (0)