useInViewport
Tracks visibility with IntersectionObserver.
Tracks visibility with IntersectionObserver.
Import
import { useInViewport } from '@kamod-ch/hooks'Live demo
Basic demo
Tracks visibility with IntersectionObserver.
Browser-only demo
This demo starts after the page mounts in the browser.
import { useRef } from 'preact/hooks'
import { useInViewport } from '@kamod-ch/hooks'
export default function UseInViewportDemo() {
const ref = useRef<HTMLDivElement>(null)
const [inViewport, ratio] = useInViewport(ref, { threshold: [0, 0.5, 1] })
return (
<div>
<div class="demo-scroll-box">
<div style={{ height: '180px' }} />
<div ref={ref} class="demo-target-box">Observed target</div>
<div style={{ height: '180px' }} />
</div>
<p><strong>Visible:</strong> {String(inViewport)} · <strong>Ratio:</strong> {ratio}</p>
</div>
)
}
API
TypeScript signature
import type { BasicTarget } from '../utils/domTarget.js';
type CallbackType = (entry: IntersectionObserverEntry) => void;
export interface Options {
rootMargin?: string;
threshold?: number | number[];
root?: BasicTarget<Element>;
callback?: CallbackType;
}
declare function useInViewport(target: BasicTarget | BasicTarget[], options?: Options): readonly [boolean, number];
export default useInViewport;
/SSR considerations
This hook touches browser APIs. Render it after mount or guard it with BrowserOnly in SSR and static builds.
Browser compatibility
Requires the corresponding browser API to exist in the current environment.