Function: useIntersectionObserver()
useIntersectionObserver<
T>(options?):UseIntersectionObserverResult<T>
Defined in: use-intersection-observer.ts:140
Tracks whether an element is visible in the viewport (or inside a scroll
container) with an IntersectionObserver, and returns it as state so your
component re-renders when visibility changes.
- Usage: attach the returned
refto any element. It is a callback ref, so it also works when the element mounts later, is rendered conditionally, or is swapped for another one. - Efficient: re-renders only when the browser reports a change, which is
when the element crosses one of the
thresholdratios. - Options:
root,rootMarginandthresholdgo straight to the observer. Inlinethresholdarrays are fine, they do not re-observe unless their values change. - Extensible: read the raw
entryfrom the result, or react to every notification withonChange, to build your own helpers. - Once:
once: truestops observing after the first time the element is seen, for lazy-loading and reveal-once animations. - Pause:
enabled: falsepauses observing and keeps the last value. - SSR-safe: returns
defaultIsIntersectingon the server, on the first render, and whereverIntersectionObserveris unavailable. - Cleanup: the observer is disconnected on unmount, when the element or
an option changes, and when
enabledbecomesfalse. When the element is detached, the result goes back to its defaults.
The first notification arrives after the element mounts, so the first render
(and the server render) uses defaultIsIntersecting. To combine the ref
with another ref, call both from a function ref, for example
ref={(el) => { ref(el); myRef.current = el; }}.
Type Parameters
T
T extends Element = HTMLElement
The type of element being observed. Defaults to HTMLElement.
Parameters
options?
UseIntersectionObserverOptions
Optional root, rootMargin, threshold, enabled, once, defaultIsIntersecting and onChange settings.
Returns
UseIntersectionObserverResult<T>
Whether the element isIntersecting, its latest entry, and the ref to attach to it.
Examples
const { ref, isIntersecting } = useIntersectionObserver<HTMLDivElement>();
return <div ref={ref}>{isIntersecting ? "Visible" : "Hidden"}</div>;
// Lazy-load an image 200px before it scrolls into view, only once
const { ref, isIntersecting } = useIntersectionObserver<HTMLImageElement>({
rootMargin: "200px",
once: true,
});
return <img ref={ref} src={isIntersecting ? src : undefined} alt="" />;
// Read how much is visible, without waiting for a re-render
const { ref } = useIntersectionObserver<HTMLElement>({
threshold: [0, 0.25, 0.5, 0.75, 1],
onChange: (entry) => console.log(entry.intersectionRatio),
});
// Compose your own helpers on top
const useIsMostlyVisible = () => {
const { ref, entry } = useIntersectionObserver<HTMLElement>({
threshold: [0, 0.5, 1],
});
return { ref, mostlyVisible: (entry?.intersectionRatio ?? 0) >= 0.5 };
};
For a live, editable example, see the useIntersectionObserver docs page.