What is IntersectionObserver used for?
BeginnerBrowser and web interview questionBy UIRound, updated 17 November 2026
Short answer
IntersectionObserver is a browser API that tells you when an element starts or stops overlapping the viewport, or another element you choose. It is used for lazy loading images and components, infinite scroll, counting ad or product impressions, highlighting the section in view, and detecting when a sticky header becomes stuck. The browser does the measuring and calls you only when visibility changes, so it is much cheaper than a scroll listener.
Basic usage
You create one observer with a callback and options, then tell it which elements to watch.
const observer = new IntersectionObserver((entries) => {
for (const entry of entries) {
if (entry.isIntersecting) {
entry.target.classList.add("visible");
observer.unobserve(entry.target); // only needed once
}
}
}, { threshold: 0.25 }); // fire when a quarter of the element is visible
document.querySelectorAll(".reveal").forEach((el) => observer.observe(el));The callback receives an array of entries, one for each observed element whose state changed. It also fires once for each element soon after observe() is called, reporting whether it is visible right now. Useful fields on each entry:
isIntersecting: whether the element overlaps the root at all.intersectionRatio: how much of it is visible, from 0 to 1.target: the element this entry is about.boundingClientRectandrootBounds: the element's and the root's rectangles at that moment.time: when the change happened.
The three options
| Option | Default | What it does |
|---|---|---|
root |
null (the viewport) |
The element whose box counts as "visible". Use a scrolling container when items scroll inside it, not the page. |
rootMargin |
"0px" |
Grows or shrinks the root's box, using CSS margin syntax ("200px 0px", "-50% 0px"). A positive value triggers early; a negative value triggers only when the element is further inside. |
threshold |
0 |
The visible ratio, or a list of ratios, at which to call back. 0 means "as soon as one pixel shows", 1 means "fully visible", [0, 0.5, 1] reports all three crossings. |
rootMargin is how you start loading before something is on screen: "300px" fires while the element is still 300 pixels below the fold. A negative margin such as "0px 0px -60% 0px" fires only when an element reaches the top 40% of the viewport, which suits a scrollspy.
What it is used for
Lazy loading
Native loading="lazy" covers images and iframes. Use an observer when you need a custom distance, a background image, a video, or a heavy component that should load only when near the viewport. The patterns and the LCP trap are covered in lazy loading for images and routes.
Infinite scroll
Put an empty "sentinel" element after the list. When it comes into view, load the next page:
const sentinel = document.querySelector("#load-more");
let loading = false;
const io = new IntersectionObserver(async ([entry]) => {
if (!entry.isIntersecting || loading) return;
loading = true;
const hasMore = await loadNextPage(); // appends items above the sentinel
loading = false;
if (!hasMore) io.disconnect();
}, { rootMargin: "400px" });
io.observe(sentinel);The loading flag stops duplicate requests. Keep a real "Load more" button too, for keyboard users and for reaching the footer.
Impressions and analytics
To count that a product card was seen, observe each card with a threshold such as 0.5, start a timer when it becomes half visible, and record an impression if it stays visible for a set time, for example one second. Cancel the timer when it leaves. unobserve each card after it is counted, so it is counted once.
Sticky headers
CSS position: sticky has no event for "now stuck". Place a one-pixel sentinel just above the header and observe it. When the sentinel scrolls out of view, the header is stuck; toggle a class to add a shadow.
new IntersectionObserver(([entry]) => {
header.classList.toggle("is-stuck", !entry.isIntersecting);
}).observe(document.querySelector("#header-sentinel"));Other common uses: pausing videos that scroll off screen, starting animations on reveal, and highlighting the current section in a table of contents.
Stopping observation
observer.unobserve(element)stops watching one element, for example after it has loaded.observer.disconnect()stops watching everything; call it when the component is removed.observer.takeRecords()returns pending entries that have not reached the callback yet.
In React, create the observer in an effect and disconnect in the cleanup:
useEffect(() => {
const el = ref.current;
if (!el) return;
const io = new IntersectionObserver(([entry]) => setVisible(entry.isIntersecting));
io.observe(el);
return () => io.disconnect();
}, []);Why it beats scroll listeners
The old way was a scroll handler that called getBoundingClientRect() on every element. Scroll events fire many times a second on the main thread, and each getBoundingClientRect() can force the browser to compute layout (see reflow vs repaint). With many elements, that causes jank. IntersectionObserver lets the browser compute intersections as part of its own rendering work and delivers results asynchronously, only when a threshold is crossed. Your code does nothing while the user scrolls through content that stays the same.
The trade-off is that callbacks are not instant or per pixel. For effects that must track scroll position exactly, such as a progress bar, a scroll listener throttled with requestAnimationFrame, or CSS scroll-driven animations, is the better tool.
Practise it
Build the classic uses in Build a lazy image loader using IntersectionObserver and Build infinite scrolling using IntersectionObserver, then wrap it in useIntersectionObserver. Log product impressions once scrolling stops and Build a scrollspy that highlights the section in view apply thresholds and margins.
Common follow-up questions
Can one observer watch many elements?
Yes, and it should. One observer with 500 targets is cheaper than 500 observers. Use entry.target in the callback to tell them apart.
Why does rootMargin not work?
Usually because the root is wrong. If items scroll inside a container, the root must be that container. With the default viewport root, the container still clips its items, so a margin on the viewport cannot reach items hidden inside it. In a cross-origin iframe, rootMargin is also ignored for the default root.
How is it different from MutationObserver and ResizeObserver?
IntersectionObserver watches visibility, MutationObserver watches changes to the DOM tree and attributes, and ResizeObserver watches an element's size. They share a similar API: create, observe, disconnect.
Does it tell me whether the element is actually visible?
No. It measures geometry only. An element covered by another element, with opacity: 0 or visibility: hidden, still counts as intersecting.
Mistakes to avoid
Creating a new observer for every element
Forgetting
disconnect()when the component is removedUsing the viewport as root for items inside a scrolling container
Assuming the callback fires only on changes; it fires once right after
observe()Not guarding against duplicate loads while a page request is in flight
Lazy-loading the image that is visible on first paint
Sources
Practise it in code
Interviewers rarely stop at the definition. These questions open in an editor with tests.
- Build a lazy image loader using
IntersectionObserverMedium35 min - Build infinite scrolling using
IntersectionObserverMedium35 minFree - Implement
useIntersectionObserver()for lazy loadingMedium35 min - Log product impressions once scrolling stopsMedium35 min
- Build a scrollspy that highlights the section in viewMedium35 min