useNearViewport turns true once an element comes within a set distance of the screen and stays true after that. Use it to postpone heavy widgets such as maps, video players and charts until the user is about to see them.
Preview
The chart below is mounted only when its block gets within 120px of the scroll box edge. Scroll back up: it stays mounted.
Scroll down inside the box
Installation
Usage
import { useNearViewport } from "@/hooks/use-near-viewport"
export function ReviewsSection() {
const [ref, isNear] = useNearViewport()
return (
<section ref={ref} className="min-h-96">
{isNear ? <ReviewsCarousel /> : null}
</section>
)
}Examples
Lazy map or video embed
An iframe starts loading its scripts as soon as it is in the DOM. Render it only when the flag turns on and keep a placeholder of the same size until then.
function MapEmbed({ src }: { src: string }) {
const [ref, isNear] = useNearViewport({ rootMargin: "300px" })
return (
<div ref={ref} className="aspect-video rounded-lg bg-muted">
{isNear && (
<iframe src={src} title="Map" className="size-full rounded-lg" />
)}
</div>
)
}Inside a scroll container
Pass the container element as root when the content scrolls inside a panel, not the page. The preview above works this way.
function Panel() {
const [root, setRoot] = useState<HTMLDivElement | null>(null)
return (
<div ref={setRoot} className="h-80 overflow-y-auto">
<Intro />
{root && <LazyChart root={root} />}
</div>
)
}
function LazyChart({ root }: { root: HTMLElement }) {
const [ref, isNear] = useNearViewport({ root, rootMargin: "120px" })
return <div ref={ref}>{isNear ? <Chart /> : <ChartSkeleton />}</div>
}Start earlier on slow widgets
A bigger rootMargin starts loading sooner, so the widget is ready by the time it scrolls into view.
// start loading a full screen before the player shows up
const [ref, isNear] = useNearViewport({ rootMargin: "100% 0px" })Parameters
| Name | Type | Default | Description |
|---|---|---|---|
| rootMargin | string | "200px" | How far from the screen edge the element counts as near, in CSS margin syntax |
| root | Element | null | null | Scroll container to watch instead of the viewport |
| disabled | boolean | false | Do not observe and keep returning false |
Returns
| Name | Type | Description |
|---|---|---|
| [0] ref | RefCallback<T> | Callback ref for the element to watch |
| [1] isNear | boolean | true once the element has come near the screen. Never resets back to false |
Features
- Fires once. The observer disconnects right after the first hit, nothing keeps running on scroll
- Fallback. Without IntersectionObserver the flag is true right away, so content is never stuck behind a placeholder
- Callback ref. Works with elements that mount later or change, no useRef and no extra effect needed