You add a scroll listener to reveal cards as they enter the screen. It works on your laptop. On a mid-range phone, scrolling stutters, the page feels heavy, and your performance report blames "long tasks." The listener runs constantly, and every call asks the browser for layout measurements it has to compute on demand.
The IntersectionObserver API fixes this by reversing the question. You stop asking "where is this element right now?" on every scroll event. You tell the browser which element you care about, and it notifies you when that element's visibility changes. This IntersectionObserver guide covers the API from the constructor to its edge cases, then builds three real features:
Lazy-loaded images
Infinite scroll
Scroll-triggered animations
Each feature comes in vanilla JavaScript and as a reusable React hook, with testing and SEO notes along the way.
If you read our ResizeObserver guide, this is its sibling. ResizeObserver tells you when an element's size changes. IntersectionObserver tells you when an element's visibility changes. Many real components use both.
What IntersectionObserver Does (and What It Doesn't)
According to MDN's Intersection Observer API documentation, the API lets you register a callback that runs whenever a target element enters or leaves an intersection with another element, or with the viewport. MDN also lists it as Baseline widely available, meaning it has worked across major browsers since March 2019.
Three terms are enough to read any IntersectionObserver code:
Target: the element you observe.
Root: the element used as the viewing area. If you leave it unset (or pass null), the root is the browser viewport. A custom root must be an ancestor of the target.
Threshold: how much of the target must be visible before your callback runs, expressed as a ratio from 0 to 1.
The browser calculates intersections itself and delivers the results asynchronously in batches, so your code does not run on every scroll tick.
One limit is worth knowing early. MDN states that the API cannot trigger logic based on the exact number of overlapping pixels. It reports ratios and a boolean, not pixel positions. For continuous scroll-linked effects such as parallax, IntersectionObserver is the wrong tool. It excels at state changes: became visible, stopped being visible, crossed a threshold.
The Anatomy: Constructor, Options and Entries
Every use of the API has the same shape:
const observer = new IntersectionObserver(callback, options);
observer.observe(targetElement);
Grows or shrinks the root's box before intersection is computed. Uses CSS margin syntax
threshold
0
One ratio or an array of ratios that trigger the callback
rootMargin is the option you will use most. A positive value makes the root effectively larger, so the callback fires before the target is visibly on screen. That is exactly what you want for preloading. A negative value shrinks the root, which is useful for "fire only when the element is well inside the screen."
// Fire when the target is within 300px of the viewport (top and bottom)
new IntersectionObserver(callback, { rootMargin: "300px 0px" });
// Fire only when the target crosses the middle band of the screen
new IntersectionObserver(callback, { rootMargin: "-40% 0px -40% 0px" });
The callback and its entries
The callback receives a list of IntersectionObserverEntry objects and the observer itself:
isIntersecting: whether the target currently intersects the root.
intersectionRatio: the visible fraction of the target, from 0 to 1.
target: the observed element, which you need when one observer watches many elements.
boundingClientRect and rootBounds: geometry snapshots, handy for knowing whether an element left through the top or the bottom.
The four methods
observe(el) starts watching an element.
unobserve(el) stops watching one element.
disconnect() stops watching everything.
takeRecords() returns pending entries immediately and empties the queue.
Behaviors that surprise people
The callback fires right after observe(). When you start observing a target, the observer reports its current state, even if nothing has scrolled yet. Your callback therefore has to handle isIntersecting: false on the first call, and it will fire for elements that are already visible on load.
Thresholds describe crossings, not states. With the default threshold of 0, the callback runs when isIntersecting flips from false to true or back. It does not keep running while the element stays visible.
Tall elements can never reach 1.0. If a target is taller than the root, it can never be 100% visible, so threshold: 1 never fires. Use a lower value or an array such as [0, 0.25, 0.5].
Hidden elements do not intersect. An element with display: none has no box, so it never intersects. Observe an element only once it is rendered.
rootMargin has a scope. Per the W3C Intersection Observer specification, rootMargin applies only to targets in the same origin context as the root. Inside cross-origin iframes the margin is ignored.
Lazy Loading Images with IntersectionObserver
Try native lazy loading first
Before writing any JavaScript, check whether the platform already solves your problem. The HTML loading="lazy" attribute on images and iframes, documented on MDN, defers offscreen loading with no script at all. Google's guide to browser-level image lazy loading recommends it as the simplest option.
Reach for IntersectionObserver when you need something the attribute cannot do:
Lazy-load CSS background images
Fade images in or show a blurred placeholder
Load a component, a script, or data (not just an image)
Control exactly how early loading starts
Run custom logic when the image loads
Do not lazy-load your largest above-the-fold image
Your Largest Contentful Paint element should load as early as possible. Google's Largest Contentful Paint guide explains why delaying the hero image hurts that metric. Apply lazy loading to images below the fold only.
Reserve space to avoid layout shift
A lazy image with no dimensions starts at zero height and pushes content down when it loads. Always set width and height attributes (or a CSS aspect-ratio) so the browser reserves the space. This protects your Cumulative Layout Shift score, covered in web.dev's CLS guide.
The vanilla JS version
Store the real URL in data-src, then swap it in when the image approaches the viewport:
<img
src="data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7"
data-src="/images/team.webp"
data-srcset="/images/team-480.webp 480w, /images/team-960.webp 960w"
sizes="(max-width: 600px) 480px, 960px"
alt="The team at a planning session"
width="960"
height="540"
>
function lazyLoadImages(selector = "img[data-src]") {
const images = document.querySelectorAll(selector);
const load = (img) => {
if (img.dataset.srcset) img.srcset = img.dataset.srcset;
img.src = img.dataset.src;
img.removeAttribute("data-src");
img.removeAttribute("data-srcset");
};
// Fallback: load everything immediately if the API is missing
if (!("IntersectionObserver" in window)) {
images.forEach(load);
return () => {};
}
const observer = new IntersectionObserver(
(entries, obs) => {
for (const entry of entries) {
if (!entry.isIntersecting) continue;
load(entry.target);
obs.unobserve(entry.target); // each image only needs to load once
}
},
{ rootMargin: "300px 0px" } // start loading 300px before it appears
);
images.forEach((img) => observer.observe(img));
return () => observer.disconnect();
}
lazyLoadImages();
The design choices matter more than the code:
One observer, many targets. A single observer watching every image is cheaper than one observer per image.
unobserve after loading. Once an image has loaded there is nothing left to watch.
rootMargin: "300px 0px". The image starts downloading before the user reaches it, so it is usually ready by the time it scrolls into view. Tune the distance to your image weight and your audience's connections.
A fallback. If the API is unavailable, load everything rather than leave blank boxes.
Lazy loading only helps if the images themselves are small. Before you ship them, run your files through the Image Compressor, and use the Image Format Converter to produce WebP or AVIF versions. If you want a tiny blurred placeholder inline in your HTML, the Image Base64 Converter turns a small image into a data URI. Loading fewer bytes also helps users on metered connections, a point we explore in our post on green coding and website energy use.
Infinite Scroll with a Sentinel Element
Infinite scroll with IntersectionObserver uses a simple pattern. Place an invisible sentinel element after your list. When the sentinel nears the viewport, load the next page and append it. The sentinel moves down, and the cycle repeats.
const list = document.querySelector("#feed");
const sentinel = document.querySelector("#feed-sentinel");
const statusEl = document.querySelector("#feed-status");
const moreButton = document.querySelector("#feed-more");
let page = 1;
let loading = false;
let hasMore = true;
function renderItem(post) {
const li = document.createElement("li");
li.textContent = post.title; // textContent avoids injecting raw HTML
return li;
}
async function loadPage() {
if (loading || !hasMore) return true;
loading = true;
statusEl.textContent = "Loading more…";
try {
const res = await fetch(`/api/posts?page=${page}`);
if (!res.ok) throw new Error(`Request failed: ${res.status}`);
const data = await res.json(); // { items: [...], hasMore: boolean }
list.append(...data.items.map(renderItem));
page += 1;
hasMore = data.hasMore;
statusEl.textContent = hasMore ? "" : "You have reached the end.";
return true;
} catch (error) {
console.error(error);
statusEl.textContent = "Could not load more items. Try again.";
return false;
} finally {
loading = false;
}
}
const observer = new IntersectionObserver(
async (entries) => {
const entry = entries.at(-1);
if (!entry?.isIntersecting) return;
const ok = await loadPage();
if (!hasMore) {
observer.disconnect();
moreButton.hidden = true;
return;
}
if (ok) rearm(); // see below
},
{ rootMargin: "0px 0px 400px 0px" } // trigger 400px before the bottom
);
function rearm() {
observer.unobserve(sentinel);
observer.observe(sentinel); // observe() reports the current state again
}
moreButton.addEventListener("click", async () => {
const ok = await loadPage();
if (ok && hasMore) rearm();
});
observer.observe(sentinel);
Three details make this version robust.
The rearm() call. Thresholds describe crossings. If the first page of content is shorter than the screen, the sentinel stays visible after you append items, so no new crossing happens and loading stops. Calling unobserve then observe makes the observer report the sentinel's current state again, which starts the next load.
The loading flag. It prevents overlapping requests if the callback fires twice in quick succession.
No rearm after an error. If the request fails and you rearmed anyway, the sentinel would still be visible and the code would retry in an endless loop. Instead, the failure leaves the user with a visible message and a button.
Keep a "Load more" button
Infinite scroll without an alternative creates real problems. Keyboard users can have trouble reaching content below the list, such as your footer. Screen reader users need to be told when new content arrives, which the role="status" element above handles. A visible button gives everyone a way to control loading, so keep it even when the observer does the work automatically.
Infinite scroll and SEO
Content that only appears through scrolling can be hard for search engines to discover. Google's documentation on pagination and incremental page loading recommends that each chunk of content be reachable through its own URL. In practice, that means real paginated pages (/blog?page=2) that work without JavaScript, with infinite scroll layered on top as an enhancement.
Scroll-Triggered Animations
Scroll-reveal animations are a natural fit for IntersectionObserver, because the question is only "did this element become visible?"
The .js prefix. Elements are hidden only when JavaScript is running. Add document.documentElement.classList.add("js") in a tiny inline script in your <head>. If your script fails to load, the content stays visible instead of being stuck at opacity: 0. Hidden content is bad for users and can be bad for search visibility.
The reduced-motion query. Some people experience discomfort from motion. The prefers-reduced-motion media feature lets you respect their system setting. Always include it.
Stick to opacity and transform for the animation. Browsers can animate those properties without recomputing layout, which keeps scrolling smooth. Our guide on optimizing heavy animations in React goes deeper on compositor-friendly CSS.
The vanilla JS version
const items = document.querySelectorAll(".reveal");
if (!("IntersectionObserver" in window)) {
items.forEach((el) => el.classList.add("is-visible"));
} else {
const revealObserver = new IntersectionObserver(
(entries, obs) => {
for (const entry of entries) {
if (!entry.isIntersecting) continue;
entry.target.classList.add("is-visible");
obs.unobserve(entry.target); // animate once, then stop watching
}
},
{ threshold: 0.15, rootMargin: "0px 0px -10% 0px" }
);
items.forEach((el) => revealObserver.observe(el));
}
The threshold: 0.15 waits until 15% of the element is visible, and the negative bottom margin delays the trigger until the element is slightly inside the screen. Together they avoid animations that fire while an element is barely peeking in. For a stagger effect, set style="--delay: 120ms" on successive elements.
Bonus: highlight the active section (scrollspy)
Observers can also drive table-of-contents highlighting. A narrow band in the middle of the screen counts as "reading this section":
Other uses follow the same pattern: pausing offscreen videos, deferring expensive widgets until they are visible, and measuring whether an element was actually seen.
Using IntersectionObserver in React
React adds two wrinkles: elements mount and unmount on their own schedule, and effects must clean up after themselves. The official React documentation on synchronizing with Effects covers this lifecycle. An observer is a perfect example of something you start in an effect and stop in its cleanup.
A reusable useIntersectionObserver hook
import { useEffect, useState } from "react";
type UseIntersectionObserverOptions = {
root?: Element | Document | null;
rootMargin?: string;
threshold?: number | number[];
once?: boolean;
};
export function useIntersectionObserver<T extends Element = HTMLElement>({
root = null,
rootMargin = "0px",
threshold = 0,
once = false,
}: UseIntersectionObserverOptions = {}) {
const [node, setNode] = useState<T | null>(null);
const [entry, setEntry] = useState<IntersectionObserverEntry | null>(null);
// A string key keeps the effect stable when callers pass an inline array.
const thresholdKey = [threshold].flat().join(",");
useEffect(() => {
if (!node || typeof IntersectionObserver === "undefined") return;
const observer = new IntersectionObserver(
(entries) => {
const latest = entries[entries.length - 1];
if (!latest) return;
setEntry(latest);
if (once && latest.isIntersecting) observer.disconnect();
},
{ root, rootMargin, threshold: thresholdKey.split(",").map(Number) }
);
observer.observe(node);
return () => observer.disconnect();
}, [node, root, rootMargin, thresholdKey, once]);
return {
ref: setNode,
entry,
isIntersecting: entry?.isIntersecting ?? false,
};
}
Why it is built this way:
A callback ref stored in state. Passing setNode as the ref means the effect re-runs whenever the element appears or disappears. A plain useRef with an empty dependency array misses elements that render later, such as ones behind a loading state, a tab, or a modal.
Cleanup in every case. The effect returns observer.disconnect(), so the observer stops when the component unmounts, when options change, and during React Strict Mode's development double-invocation.
SSR safety. The observer is created only inside an effect, which never runs on the server. In the Next.js App Router, files that use hooks need the "use client" directive.
A stable threshold key. An inline threshold={[0, 0.5]} creates a new array on every render, which would tear down and recreate the observer each time. Joining it into a string avoids that.
If you want to see how React's own subscription primitive handles external browser APIs, our useSyncExternalStore guide is a useful companion.
The same CSS from the vanilla section applies unchanged. Because of once: true, the observer disconnects after the first reveal, and the component keeps its is-visible class.
Example 2: lazy-loading images in React
In most React apps, the simplest lazy image is the native attribute:
React's rendering model gives you the "rearm" step for free. When loading finishes, the status changes, the effect runs again, and if the sentinel is still visible, the next page loads.
Pass a stable fetchPage function (defined outside the component or wrapped in useCallback), or loadMore will change on every render. Then use the hook in a component:
import { useInfiniteFeed } from "./useInfiniteFeed";
type Post = { id: string; title: string };
async function fetchPosts(page: number) {
const res = await fetch(`/api/posts?page=${page}`);
if (!res.ok) throw new Error(`Request failed: ${res.status}`);
return (await res.json()) as { items: Post[]; hasMore: boolean };
}
export function Feed() {
const { items, status, sentinelRef, loadMore } = useInfiniteFeed<Post>(fetchPosts);
return (
<section aria-labelledby="feed-title">
<h2 id="feed-title">Latest posts</h2>
<ul>
{items.map((post) => (
<li key={post.id}>{post.title}</li>
))}
</ul>
{status === "loading" && <p role="status">Loading more…</p>}
{status === "error" && (
<button type="button" onClick={loadMore}>
Could not load. Retry
</button>
)}
{status === "idle" && (
<button type="button" onClick={loadMore}>
Load more
</button>
)}
{status === "done" && <p>You have reached the end.</p>}
{status !== "done" && (
<div ref={sentinelRef} style={{ height: 1 }} aria-hidden="true" />
)}
</section>
);
}
When the response shape is unfamiliar, paste a sample payload into our JSON to TypeScript Converter to generate the Post type instead of writing it by hand. The error path matters here too: because error is not idle, the effect does not retry automatically, and the user decides when to try again.
Performance Tips
Share observers for long lists. The hook above creates one observer per element, which is fine for dozens of items. For hundreds of targets, share a single observer and call observe on each element.
Keep callbacks light. Entries arrive in batches. Do minimal work inside the callback, such as toggling a class or updating state, and defer heavier work.
Unobserve what you are done with. Animate-once and load-once patterns should always call unobserve or disconnect.
Avoid unnecessary state updates. Storing every entry in state re-renders your component on each threshold crossing. If you only need a boolean, store a boolean. If you pass an array of thresholds, consider an onChange callback instead of state.
Do not combine this with scroll listeners for the same job. If an observer handles it, delete the scroll handler.
Testing IntersectionObserver Code
Test environments such as jsdom do not implement IntersectionObserver, so you provide a mock that lets you trigger visibility on demand. Here is one for Vitest:
With React Testing Library (and @testing-library/jest-dom for toHaveClass), a test for the Reveal component looks like this:
import { act, render, screen } from "@testing-library/react";
import { expect, test } from "vitest";
import { Reveal } from "./Reveal";
import { MockIntersectionObserver } from "./mockIntersectionObserver";
test("adds is-visible when scrolled into view", () => {
render(<Reveal>Hello</Reveal>);
const el = screen.getByText("Hello");
expect(el).not.toHaveClass("is-visible");
act(() => {
MockIntersectionObserver.instances[0].trigger(el, true);
});
expect(el).toHaveClass("is-visible");
});
Mocks verify your logic, not the browser's geometry. Pair them with a manual check in a real browser, throttled to a slow connection, to confirm that images load early enough and that nothing jumps around.
ResizeObserver and IntersectionObserver complement each other. A virtualized list, for example, uses one to measure rows and the other to decide which rows are on screen. Our ResizeObserver guide covers the measuring half.
Accessibility and SEO Checklist
Prefer native lazy loading where it is enough. Fewer scripts mean fewer failure modes.
Make sure lazy content actually loads for crawlers. Google's lazy-loading guidance for Search says lazy-loaded content should load when it becomes visible in the viewport. Verify with the URL Inspection tool in Search Console.
Provide paginated URLs behind infinite scroll. Each chunk of content should be reachable without scrolling or running JavaScript.
Never leave content permanently hidden. Gate reveal animations behind a .js class and a reduced-motion query.
Announce changes. Use role="status" or aria-live="polite" for loading messages, and do not move keyboard focus when new items arrive.
Keep a visible "Load more" button so keyboard users can reach the footer.
Set width and height on every lazy image to prevent layout shift.
Common Mistakes and How to Fix Them
Lazy-loading the hero image. This delays your Largest Contentful Paint. Lazy-load only images below the fold.
Forgetting that the callback fires on observe(). Your code runs once with the initial state. Check isIntersecting before acting.
Using threshold: 1 on tall elements. An element taller than the root can never be fully visible. Use a smaller threshold or an array.
Never disconnecting. Observers kept alive after their elements are gone leak memory. Disconnect in effect cleanup or when you are finished.
Infinite loops after errors. Re-observing a still-visible sentinel after a failed request retries forever. Rearm only after success and offer a retry button.
Missing space reservations. Images without dimensions cause layout shift. Set width and height.
Passing a new options object or array every render in React. This recreates the observer constantly. Use primitive values or a stable key, as the hook above does.
Observing an element that is not rendered.display: none targets never intersect. Observe after the element is part of the layout.
Ignoring users who prefer less motion. Always wrap reveal animations in a prefers-reduced-motion check.
Frequently Asked Questions
What is IntersectionObserver used for?
It detects when an element enters or leaves the viewport (or another element) without a scroll listener. Common uses are lazy loading images, infinite scroll, scroll-triggered animations, scrollspy navigation, and pausing offscreen media.
Is IntersectionObserver better than a scroll event listener?
For visibility checks, yes. The browser computes intersections and sends batched, asynchronous notifications, so your code does not run on every scroll tick or force repeated layout reads. For effects that must follow the scroll position continuously, such as parallax, a scroll-based approach is still the right fit.
Does IntersectionObserver work in React?
Yes. Create the observer in a useEffect, observe a DOM node obtained through a ref, and disconnect in the cleanup function. The useIntersectionObserver hook in this guide packages that pattern, including support for elements that mount later.
What does rootMargin do?
It grows or shrinks the root's box before intersection is calculated, using CSS margin syntax. Positive values trigger callbacks earlier (useful for preloading), and negative values trigger them later.
Should I still use loading="lazy" on images?
In most cases, yes. It needs no JavaScript and works well for simple deferral. Use IntersectionObserver when you need custom behavior such as background images, fade-ins, component loading, or a specific preload distance.
Is IntersectionObserver supported in all browsers?
MDN lists it as Baseline widely available, with support across major browsers since March 2019. A small fallback, such as loading content immediately when the API is missing, covers the remaining edge cases.
Key Takeaways
IntersectionObserver turns "where is this element?" into "tell me when its visibility changes," which keeps scrolling smooth.
rootMargin controls when callbacks fire, and threshold controls how much must be visible.
Use native loading="lazy" first, and IntersectionObserver for custom lazy loading, sentinels, and animations.
A sentinel element plus a loading guard is a reliable infinite scroll pattern, but only if you rearm it correctly and keep a "Load more" button and real paginated URLs.
In React, store the observed node in state, create the observer in an effect, and always clean up.
Reserve space for lazy content, respect reduced motion, and never leave content hidden when JavaScript fails.